Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Comparison of dates in PHP
Comparing two dates in PHP is straightforward when both dates are in a similar format, but PHP may fail to analyze dates when they are in different formats. In this article, we will discuss different approaches to date comparison in PHP using simple operators, the strtotime() function, and the DateTime class.
Case 1: Simple Comparison with Same Format
You can compare dates using simple comparison operators if the given dates are in the same format ?
<?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";
?>
2018-11-24 is older than 2019-03-26
Here we declared two dates in the same Y-m-d format, allowing direct string comparison since PHP compares them lexicographically.
Case 2: Using strtotime() for Different Formats
When dates are in different formats, use the strtotime() function to convert them into UNIX timestamps for comparison ?
<?php
$date1 = "18-03-22";
$date2 = "2017-08-24";
$timestamp1 = strtotime($date1);
$timestamp2 = strtotime($date2);
if ($timestamp1 > $timestamp2)
echo "$date1 is latest than $date2";
else
echo "$date1 is older than $date2";
?>
18-03-22 is latest than 2017-08-24
The strtotime() function converts different date formats into numeric UNIX timestamps, which can then be compared using standard operators.
Case 3: Using DateTime Objects
The DateTime class provides the most robust approach for date comparison, handling various formats automatically ?
<?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 'datetime1 is equal to datetime2';
}
?>
datetime1 lesser than datetime2
DateTime objects can be compared directly using comparison operators, and PHP automatically handles the date parsing and comparison logic.
Conclusion
Use simple string comparison for same-format dates, strtotime() for mixed formats, and DateTime objects for the most reliable and feature-rich date comparisons in PHP.
