Compare dates

How correct is it to compare dates in this way?

$today = date('Y-m-d'); 
$outdate = "2011-11-02";

if($today >= $outdate) {...

Previously, I know it was necessary to translate into different timestamps, but it looks like now, if you set the date in this format. everything should be OK, shouldn't it?

Author: Sh4dow, 2011-10-02

3 answers

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

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

But if you are not sure that the date format is the same, then it is better to convert 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
 12
Author: Lorik, 2011-10-02 20:52:21

Use the strtotime function, i.e. translate your strings that you get via date into a unix timestamp, i.e. into an int number, and then you can conveniently compare

 3
Author: iurii_n, 2011-10-02 17:34:28

You can not compare dates as strings in any case, this will not be correct if you have:

$date1 = '01.03.1956';
$date2 = '05.06.1930';

Expression $date2 > $date1 ? true : false; Returns true for the reason that the strings are compared character-by-character, respectively, since 5 > 1, the string $date2 > $date1.

Of course, the 2011-02-12 format will return a valid comparison, but this is potentially dangerous code.

 1
Author: Святослав Карамушко, 2020-03-30 06:26:19