compare dates php – 5 Ways to compare two dates in php

compare dates php: you can easy and simply compare to date in php. Given two dates (first_dt and second_dt) and the task is to compare the given dates.

compare dates php

In order to compare those two dates we use the method diff() of the first DateTime object with the second DateTime object as argument.

How To Compare Dates In PHP – Simple Examples

Example 1:

<!--?php $first_date=date_create("2022-04-12"); $second_date=date_create("2022-12-12"); $final_diff=date_diff($first_date,$second_date); echo $final_diff->format("%R%a days");<br ?--> ?>

Example 2: COMPARISON WITH UNIX TIMESTAMP

<!--?php //UNIX TIMESTAMP $first_date = strtotime("2022-08-07"); $second_date = strtotime("2015-08-09"); //CAN BE COMPARED USING OPERATORS if ($first_date > $second_date) { echo "first_date is later"; }<br ?--> else if ($first_date < $second_date) { echo "second_date is later"; }
else { echo "first_date second_date are the same"; }

Example 3: DATE STRING COMPARISON

<!--?php //WORKS IF DATE IS IN YYYY-MM-DD $first_date = "2022-08-07"; $second_date = "2022-10-11"; if ($first_date > $second_date) { echo "first_date is later"; }<br ?--> else if ($first_date < $second_date) { echo "second_date is later"; }
else { echo "first_date second_date are the same"; }

Example 4: COMPARING MULTIPLE DATES

<!--?php //ARRAY OF DATES $dates = ["2025-04-05", "2022-04-05", "2024-06-05", "2023-08-07"]; //UNIX TIMESTAMP $unix = []; foreach ($dates as $d) { $unix[] = strtotime($d); } //SORT HIGH TO LOW arsort($unix); foreach ($unix as $k=>$u) {<br ?--> echo "$k - " . date("Y-m-d", $u)."
";
}

Don’t Miss: How To Compare Date In Php?

Read Also:  How To Add Flash Messages in Laravel 6 Session?

Example : 5 3-string.php

<!--?php NOT WORK $first_date = "22 APR 2021"; $second_date = "22 JAN 2021"; if ($first_date > $second_date) { echo "first_date is later"; }<br ?--> else if ($first_date < $second_date) { echo "second_date is later"; }
else { echo "Asecond_date are the same"; }

I hope you get an idea about compare dates php.
I would like to have feedback on my infinityknow.com.
Your valuable feedback, question, or comments about this article are always welcome.
If you enjoyed and liked this post, don’t forget to share.