Comparison of dates in PHP


Matching two dates in PHP is quite smooth when both the dates are in a similar format but php failed to analyze when the two dates are in an unrelated format. In this article, we will discuss different cases of date comparison in PHP. We will figure out how to utilize DateTime class,strtotime() in comparing dates.

Case 1:

we can analyze the dates by simple comparison operator if the given dates are in a similar 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";
?>

Output:

2019-03-26 is latest than 2018-11-24

Explanation:

Here we have declared two dates $date1 and $date2 in the same format. So we have used a comparison operator(>) to compare the dates.

Case 2:

If the given dates are in various formats at that point we can utilize the strtotime() function to convert the given dates into the UNIX timestamp format and analyze these numerical timestamps to get the expected result.

Example:

<?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";
?>

Output:

18-03-22 is latest than 2017-08-24

Explanation:

In this example, we have two Dates which are in a different format. So we have used predefined function strtotime() convert them into numeric UNIX timestamp, then to compare those timestamps we use different comparison operators to get the desired result.

Case 3:

Comparing two dates by creating the object of the DateTime class.

Example:

<?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';
   }
?>

Output:

datetime1 lesser than datetime2

Explanation:

In this example, we created two DateTime objects. In order to compare those two dates, we use different comparison operators to get the desired result.

Updated on: 30-Jul-2019

5K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements