$date2)ech"/> $date2)ech">

Home  >  Article  >  Backend Development  >  Comparison of dates in PHP

Comparison of dates in PHP

王林
王林forward
2023-09-09 17:21:071093browse

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.

Case 1:

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

Output:

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

Explanation:

Here we declare two dates $date1 and $date2 in the same format. Therefore, we use the comparison operator (>) to compare dates.

Case 2:

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.

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 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.

Case 3:

Compare two dates by creating an object of DateTime class.

Example:

<?php
   $date1 = new DateTime("18-02-24");
   $date2 = new DateTime("2019-03-24");
   if ($date1 > $date2) {
    echo &#39;datetime1 greater than datetime2&#39;;
   }
   if ($date1 < $date2) {
    echo &#39;datetime1 lesser than datetime2&#39;;
   }
  if ($date1 == $date2) {
    echo &#39;datetime2 is equal than datetime1&#39;;
   }
?>

Output:

datetime1 lesser than datetime2

Explanation:

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!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete