Home > Enterprise >  Comparing 2 dates to the current date and make active or expired [duplicate]
Comparing 2 dates to the current date and make active or expired [duplicate]

Time:10-06

I am trying to work out I have 2 dates and I want to have them compared to todays date. If both dates are greater that today make status active else expired. If 1 date is greater (active) and the other is less than today it should change to expired. Here is my code. I cannot get this to work correctly. I cannot work out what I am missing

$currentDate = date('Y-m-d');
$currentDate = date('Y-m-d', strtotime($currentDate));

$date1 = date('Y-m-d', strtotime("22/10/2021"));
$date2 = date('Y-m-d', strtotime("23/08/2021"));

if (($date1 > $currentDate) && ($date2 > $currentDate)) {
    echo "Active";
} else {
    echo "Expired";
}

CodePudding user response:

In php strtime() documentation:

The best way to compensate for this is by modifying your joining characters. Forward slash (/) signifies American M/D/Y formatting, a dash (-) signifies European D-M-Y and a period (.) signifies ISO Y.M.D.

Observe:

<?php
echo date("jS F, Y", strtotime("11.12.10"));
// outputs 10th December, 2011
echo date("jS F, Y", strtotime("11/12/10"));
// outputs 12th November, 2010
echo date("jS F, Y", strtotime("11-12-10"));
// outputs 11th December, 2010 
?>

So: change your date formate in strtime() function like this

$currentDate = date('Y-m-d');
  $currentDate = date('Y-m-d', strtotime($currentDate));

  $date1 = date('Y-m-d', strtotime("10/22/2021"));
  $date2 = date('Y-m-d', strtotime("08/23/2021"));

  if (($date1 > $currentDate) && ($date2 > $currentDate))
  {
      echo "Active";
  }else{
      echo "Expired";
    }

CodePudding user response:

You didn't respect the 'Y-m-d' format. You want to convert your dates to 'Y-m-d', but you passed them as 'd/m/Y'.

Try to change your lines :

$date1 = date('Y-m-d', strtotime("22/10/2021"));
$date2 = date('Y-m-d', strtotime("23/08/2021"));

by :

 $date1 = date('Y-m-d', strtotime("2021-10-22"));
 $date2 = date('Y-m-d', strtotime("2021-08-23"));

CodePudding user response:

I think you can try this

<?php

$currentDate = date('Y-m-d');
$currentDate = date(strtotime($currentDate));

$date1 = new DateTime();
$date1->setDate(2021, 10, 22);
$date1 = $date1->getTimestamp();

$date2 = new DateTime();
$date2->setDate(2021, 8, 23);
$date2 = $date2->getTimestamp();

if (($date1 > $currentDate) && ($date2 > $currentDate)) {
    echo "Active";
} else {
    echo "Expired";
}
  • Related