How to compare dates in PHP

php_date_compareHow to actually compare 2 dates in PHP with each other? The question sounds easier than it is.  The first thought that usually comes is the following. We store both dates as strings and compare them.

Preliminary

<?php
$date1 = "2012-1-12";
$date2 = "2011-10-12";

if ($date1 > $date2)
 echo "$date1 is newer than $date2";
else
 echo "$date1 is older than $date2";
?>

Output:

2012-1-12 is newer than 2011-10-12

At first glance this seems to be a workable solution. But what if the two data is in a different format?

<?php
$date1 = "12-1-12";
$date2 = "2011-10-12";

if ($date1 > $date2)
 echo "$date1 is newer than $date2";
else
 echo "$date1 is older than $date2";
?>

Output:

12-1-12 is older than 2011-10-12

Now the date in 2012 is declared to be older than the date in 2011, which is of course wrong. However, from PHP’s point of view, this behavior is correct, because two strings were compared and so the 2012 date string was definitely the smaller/shorter string.

How to properly compare dates in PHP

A working solution would be to first convert the date into timestamp format and then to compare these numerical timestamps each other. To convert a date string into a timestamp, PHP provides the function strtotime ($time_string), which accepts a date or a time value and returns the corresponding timestamp.

<?php
$date1 = "12-1-12";
$date2 = "2011-10-12";
$dateTimestamp1 = strtotime($date1);
$dateTimestamp2 = strtotime($date2);

if ($dateTimestamp1 > $dateTimestamp2)
 echo "$date1 is newer than $date2";
else
 echo "$date1 is older than $date2";
?>

Output:

12-1-12 is newer than 2011-10-12

However, well known, many roads lead to Rome, so there are still other solutions for the initial problem. So one of these alternative solutions would be to use the DateTime class that is provided by PHP as of version 5.2.0.

<?php
$date1 = new DateTime("12-1-12");
$date2 = new DateTime("2011-10-12");

if ($date1 > $date2)
 echo $date1->format("Y-m-d")." is newer than ".$date2->format("Y-m-d");
else
 echo $date1->format("Y-m-d")." is older than ".$date2->format("Y-m-d");
?>

Output:

2012-01-12 is newer than 2011-10-12

How do you compare two dates in PHP? Do you use one of the two identified ways or is it another? I would be interested to know how you solve yourself the problem.

1 Comments

  1. good information is importat to people

Leave a comment

Please be polite. We appreciate that. Your email address will not be published and required fields are marked