Compare dates using PHP

In this tutorial, we will use a PHP date compare method to determine which of two (or more) dates is earlier or later. This is extremely handy in various applications where we want to know which of a set of dates came first, for example, in a scheduling or ordering application.

PHP has a built-in function called strtotime which makes life a lot easier for anyone who wants to use PHP to compare dates. The strtotime function simply takes a date as its parameter and returns a timestamp representing that date. The timestamp is simply a number which tells the amount of seconds between the Unix Epoch and the given date.

PHP strtotime Examples

The strtotime function, which powers our method, is shown below at work in the following script:

<?php
 
echo strtotime('2008-08-12 19:24') . '<br />';
echo strtotime('19 march 2008 11:24') . '<br />';
echo strtotime('now') . '<br />';
echo strtotime('+3 days') . '<br />';
echo strtotime('next thursday') . '<br />';
 
?>

The results are some numeric timestamps that we can compare arithmetically!

1218590640
1205947440
1490337561
1490596761
1490853600

Now you know how to get timestamps from dates, we can go on to the actual PHP date comparison.

PHP Date Compare Example

Since we know how to convert a date to a corresponding number (its timestamp), we can then use regular PHP comparison operators to determine which date is "larger" or later.

Look at the following code:

<?php
 
$date_1 = '2012-01-01 12:54';
$date_2 = '2011-03-02 05:23';
 
if (strtotime($date_2) > strtotime($date_1))
{ 
	echo 'Date 2 is later than Date 1';
}
else
{
	echo 'Date 1 is later than Date 2';
}
 
?>

The result:

Date 1 is later than Date 2

Advanced Example of the PHP Date Comparing

We can also do some fancy things with our input dates since the strtotime function has a versatile range of inputs. Have a look at this:

<?php
 
$date_1 = '+2 days';
$date_2 = 'next tuesday';
 
if (strtotime($date_2) > strtotime($date_1))
{ 
	echo "$date_2 comes after $date_1";
}
else
{
	echo "$date_2 comes before $date_1";
}
 
?>

The result, which clearly depends on the day today is, may be something like this:

next tuesday comes after +2 days

Note that there are other ways of comparing dates in PHP, but the method of checking which timestamp is greater than the other is probably the easiest method you will come across.

Now you should have all you need to get started on comparing dates with PHP. We hope you found this PHP date compare tutorial useful.

Thank Tutorial Arena for This Tutorial.
Show your appreciation with a +1...