0

I have this code to compare:

 $dateregister = date("d/m/Y", strtotime($register['date']));
   if ($dateregister < date('d/m/Y')) {
      $class = 'danger';
   } else {
     $class = '';
   }

Always enter in if, but some dates ($dateregister) are bigger than date(d/m/Y)

user115812
  • 9
  • 2
  • 7
  • [date](http://php.net/manual/en/function.date.php) returns a string, so you are actually comparing two strings. Better use [DateTime](http://php.net/manual/en/intro.datetime.php) class! – Jeff Jun 27 '18 at 18:21
  • You are doing a plain string comparison. `2/1/1999 > 1/1/2018`. If you really dont want to use DateTime class, then compare by: `date('Ymd')` instead (treats it as an int). – IncredibleHat Jun 27 '18 at 18:21
  • Thank you, my `dateregister` is in d/m/Y format – user115812 Jun 27 '18 at 18:23
  • So? You are turning `$register['date']` into a timestamp, and turning it back into a string. And doing a string compare. What exactly is inside `$register['date']` ? Do a [DateTime::createFromFormat](http://php.net/manual/en/datetime.createfromformat.php) and then compare with today using the class methods. – IncredibleHat Jun 27 '18 at 18:28
  • 31/01/18 or 310118 is > then 15/12/18 or 151218, with dates you shouldn't be comparing the string values. Just looking for a dupe, its been answered before many times. – Lawrence Cherone Jun 27 '18 at 18:29

1 Answers1

1
$dateRegister = strtotime($register['date']);
if($dateRegister < strtotime(date('d/m/Y'))){
     $class = "danger";
}else{
     $class = "";
}

I am sure it will be helpful because strtotime returns timestamp and it executes exact comparing operators

Otherwise you should use Date Class and it's easy to get comparison of 2 dates.

$today = new DateTime('');
$expireDate = new DateTime($row->expireDate); //from database

if($today->format("Y-m-d") < $expireDate->format("Y-m-d")) { 
   //do something; 
}
Naveed Ramzan
  • 3,565
  • 3
  • 25
  • 30