This article demonstrates how to compare two dates in PHP.

1. Using strtotime() function

A simple solution is to convert both dates into Unix timestamps and compare the timestamps to determine the order of dates. You can use the strtotime() function to parse a string containing an English date format into a Unix timestamp, which then can be compared using comparison operators.

Download  Run Code

 
If your dates are always in the English date format ('YYYY-MM-DD'), you can perform simple string comparisons to determine if the first date is less than, greater than, or equal to the second date.

Download  Run Code

2. Using DateTime class

Alternatively, you could use the DateTime class to perform a comparison between two dates. The advantage of using this method is that it can parse any date and time string in the specified format. The following example shows how you can compare two DateTime objects using comparison operators:

Download  Run Code

 
To find the datetime difference between two dates, you can use the DateTime::diff() function. Since it returns the DateInterval object, use the DateInterval::format() function with the formatting option '%R%a' to get the number of days.

Download  Run Code

That’s all there is to comparing two dates in PHP.