How to compare two dates in PHP?

I am explaining you, how to compare two dates in PHP.
Provided two dates (checkdate1 and checkdate2) and the task is to compare the two dates. Comparing two dates in PHP when the two dates are in the same format. we can compare two dates if it is in same format so directly we can check and other way we can check with the use of timestamp() function.

Example 1: Compating two dates in PHP with same date format.

<?php 
  $checkdate1 = "2018-10-20";
  $checkdate2 = "2022-10-14";  
  if ($checkdate1 < $checkdate2) 
    echo "$checkdate1 is less than $checkdate2"; 
  else
    echo "$checkdate1 is greater than $checkdate2";
?>

Result:

2018-10-20 is less than 2022-10-14

Example 2: How to compare two dates in PHP with strtotime() function

If provided two dates are in different formats, use the strtotime() function to convert provided dates into corresponding “timestamp” format.

<?php 
  $checkdate1 = "2018-10-20"; 
  $checkdate2 = "2022-10-14"; 
  $timestamp1 = strtotime($checkdate1); 
  $timestamp2 = strtotime($checkdate2); 
  if ($timestamp1 > $timestamp2)
    echo "$checkdate1 is greater than $checkdate2";
  else
    echo "$checkdate1 is less than $checkdate2"; 
?>

Result:

2018-10-20 is less than 2022-10-14

Leave a Reply

Your email address will not be published. Required fields are marked *

68 − = 64