You are here: Home / Topics / How to compare two dates in PHP

How to compare two dates in PHP

Filed under: PHP on 2023-06-30 06:38:36

Given two dates (date1 and date2) and the task is to compare the given dates. Comparing two dates in PHP is simple when the two dates are in the same format, but the problem arises when the two dates are in a different format.
 

Method 1: How to compare two dates in PHP


If the given dates have the same format, use a simple comparison operator to compare the dates.

<?php 
 $date1 = "2010-01-15";
 $date2 = "2020-12-14";  
 if ($date1 < $date2) 
   echo "$date1 is less than $date2"; 
 else
   echo "$date1 is greater than $date2";
?>
 

Output:

2010-01-15 is less than 2020-12-14
 

 

Method 2: How to compare two dates in PHP


If the two given dates are in different formats, use the strtotime() function to convert the given dates into the corresponding “timestamp” format and finally compare them to get the desired result.

<?php 
 $date1 = "2010-01-15"; 
 $date2 = "2020-12-14"; 
 $timestamp1 = strtotime($date1); 
 $timestamp2 = strtotime($date2); 
 if ($timestamp1 > $timestamp2)
   echo "$date1 is greater than $date2";
 else
   echo "$date1 is less than $date2"; 
?>
 

Output:

2010-01-15 is less than 2020-12-14


About Author:
V
Vinay Kumar     View Profile
Hi, I am using MCQ Buddy. I love to share content on this website.