How to compare two dates in php
How to compare two dates in php

How to compare two dates in php

How to compare two dates in php

If we want to compare two dates date one and date two.
We have 3 ways to Compare two dates in PHP.

1) If both dates are in the same format

Method 1: If both dates are in the same format then use comparison operator.

Example:

<?php

// initialize dates
$date1 = “2018-05-05”;
$date2 = “2019-08-19”;

//comparison operator to

if ($date1 > $date2) {
echo “$date1 is latest than $date2”;
}
else{
echo “$date1 is older than $date2”;
}

?>

Output:
2018-05-05 is older than 2019-08-19

Method 2: If both dates are in different formats then we need to use strtotime() function to convert dates into the timestamp format

<?php

// initialize dates

$date1 = “18-05-05”;
$date2 = “2019-08-19”;

$dateTimestamp1 = strtotime($date1);
$dateTimestamp2 = strtotime($date2);

//converted dates
if ($dateTimestamp1 > $dateTimestamp2)
{
echo “$date1 is latest than $date2”;
}
else{
echo “$date1 is older than $date2”;
}

?>
Output:
18-05-05 is older than 2019-08-19

Method 3: Use DateTime class.

Example:
<?php

// initialize dates

$date1 = new DateTime(“18-05-05”);
$date2 = new DateTime(“2019-08-19”);

// Compare the dates
if ($date1 > $date2) {
echo $date1->format(“Y-m-d”) . ” is latest than ”
. $date2->format(“Y-m-d”);
}
else{
echo $date1->format(“Y-m-d”) . ” is older than ”
. $date2->format(“Y-m-d”);
}

?>
Output:
2018-05-05 is older than 2019-08-19