How to compare two dates in php [duplicate]

How to compare two dates in php if dates are in format '03_01_12' and '31_12_11' .

I am using this code:

$date1=date('d_m_y');
$date2='31_12_11';
if(strtotime($date1) < strtotime($date2))
   echo '1 is small ='.strtotime($date1).','.$date1;
else
   echo '2 is small ='.strtotime($date2).','.$date2;

But its not working..


You will have to make sure that your dates are valid date objects.

Try this:

$date1=date('d/m/y');
$tempArr=explode('_', '31_12_11');
$date2 = date("d/m/y", mktime(0, 0, 0, $tempArr[1], $tempArr[0], $tempArr[2]));

You can then perform the strtotime() method to get the difference.


Using DateTime::createFromFormat:

$format = "d_m_y";
$date1  = \DateTime::createFromFormat($format, "03_01_12");
$date2  = \DateTime::createFromFormat($format, "31_12_11");

var_dump($date1 > $date2);

Not answering the OPs actual problem, but answering just the title. Since this is the top result for "comparing dates in php".

Pretty simple to use Datetime Objects (php >= 5.3.0) and Compare them directly

$date1 = new DateTime("2009-10-11");
$date2 = new DateTime("tomorrow"); // Can use date/string just like strtotime.
var_dump($date1 < $date2);