How to compare two dates in PHP

PHP

In this tutorial, we will learn how to compare two dates in PHP.

Example 1: If the dates are in the same format, then we will use a comparison operator.

<?php
$date1 = “2022-01-01”;
$date2 = “2022-06-29”;
if ($date1 < $date2) {
echo “$date1 is less than $date2”;
else{
echo “$date1 is greater than $date2”;
}
?>

Output: 2022-01-01 is less than 2022-06-29

Example 2: If both dates are in different formats then use strtotime() the function to convert the given dates into the corresponding timestamp format. After that compare using the comparison operator.

<?php
$date1 = “2022-01-01”;
$date2 = “2022-06-29”;
$timestamp1 = strtotime($date1);
$timestamp2 = strtotime($date2);
if ($timestamp1 > $timestamp2){
echo “$date1 is greater than $date2”;
}
else{
echo “$date1 is less than $date2”;
}
?>

Output: 2022-01-01 is less than 2022-06-29

The post How to compare two dates in PHP appeared first on PHPGurukul.