How correct is it to compare dates in this way?

$today = date('Ym-d'); $outdate = "2011-11-02"; if($today >= $outdate) {... 

I used to know it was necessary to translate into different timestamps, but it seems now, if you set the date in this format. everything should be ok, isn't it?

  • one
    Hardly because in this case you are comparing strings. - Barton
  • one
    @AlexWindHope Lie! Compare this $curdate = date('dmY', strtotime('now')); $revenge_date = "25.05.2015"; $curdate = date('dmY', strtotime('now')); $revenge_date = "25.05.2015"; if there are first days of the month, then they will be less than 25, even though the year will be longer. And the code will not work correctly! - I_CaR

2 answers 2

If the dates are exactly in the same format, then it makes sense to compare them as strings, i.e.

 $date1='2011-02-12'; $date2='2012-02-13'; $result=($date1<$date2); //$result === true 

But if there is no certainty that the format of dates is the same, then it is better to bring them to the unixtime format and compare them as numbers:

 $date1='2011-02-12'; $date2='13.02.2012'; $result=($date1<$date2); //$result === false $result=(strtotime($date1)<strtotime($date2)); //$result === true 
  • Well, almost the same as I wrote only in the code, I agree - Barton
  • four
    > If the dates are exactly in the same format, then it makes sense to compare them as strings, i.e. This is not quite true. In order for the string comparison to work correctly, you need not only that the format matches, but also that this format conforms to the ISO 8601 standard , according to which the date is written in descending order of significance. Those. version date('dmY') >= '02.11.2011' will not work anymore, even though the format is the same. - Ilya Pirogov
  • In general, it is better to compare the strcmp function, but most likely it is called, implicitly - Alex Kapustin

Use the strtotime function, i.e. translate your strings that you get through date to the unix timestamp, i.e. to the number int and then it is convenient to compare

  • And the difference? in this case, it is simply not there ... - Zowie
  • How is it not ?? - Dem
  • one
    really, how is it not? compare strings and numbers no difference? do this example yourself and see) - Barton
  • @Barton, @Dem plz explain the difference of comparing strings and numbers, when the difference between dates is not needed? - Sh4dow
  • In general, if the integers are stored as strings, then there is no difference, but with the float in the rows already have to play. In this case, @Loric wrote correctly. but how do we know that the dates will always be in the same format? therefore, we resort to using the f-i transfer to int - Barton