$date2)ech"/> $date2)ech">
Home > Article > Backend Development > Comparison of dates in PHP
In PHP, matching two dates goes very smoothly when they have similar formats, but when two dates have unrelated formats, PHP fails to parse. In this article, we will discuss the different scenarios of date comparison in PHP. We will find out how to compare dates using the DateTime class and strtotime() function.
If the given dates have similar formats, we can analyze these dates through simple comparison operators.
<?php $date1 = "2018-11-24"; $date2 = "2019-03-26"; if ($date1 > $date2) echo "$date1 is latest than $date2"; else echo "$date1 is older than $date2"; ?>
2019-03-26 is latest than 2018-11-24
Here we declare two dates $date1 and $date2 in the same format. Therefore, we use the comparison operator (>) to compare dates.
If the given date is in various formats at this time, we can use the strtotime() function to convert the given date to UNIX timestamp format and analyze these numeric timestamps to obtain the expected results.
<?php $date1 = "18-03-22"; $date2 = "2017-08-24"; $curtimestamp1 = strtotime($date1); $curtimestamp2 = strtotime($date2); if ($curtimestamp1 > $curtimestamp2) echo "$date1 is latest than $date2"; else echo "$date1 is older than $date2"; ?>
18-03-22 is latest than 2017-08-24
In this example, we have two dates represented in different formats. Therefore, we convert them into numeric UNIX timestamps using the predefined function strtotime() and then compare these timestamps using different comparison operators to get the desired result.
Compare two dates by creating an object of DateTime class.
<?php $date1 = new DateTime("18-02-24"); $date2 = new DateTime("2019-03-24"); if ($date1 > $date2) { echo 'datetime1 greater than datetime2'; } if ($date1 < $date2) { echo 'datetime1 lesser than datetime2'; } if ($date1 == $date2) { echo 'datetime2 is equal than datetime1'; } ?>
datetime1 lesser than datetime2
In this example, we create two DateTime objects. To compare these two dates, we use different comparison operators to get the desired result.
The above is the detailed content of Comparison of dates in PHP. For more information, please follow other related articles on the PHP Chinese website!