- 5 years ago
- Zaid Bin Khalid
- 34,733 Views
-
9
In this tutorial, I will explain to you how you can compare two dates in PHP. Compare two dates in PHP is very simple if both dates have the same format but the problem when date1 and date2 both have different formats.
First Method
When both dates have the same format then you can compare both dates as below.
<?php
//Date formate is (YYYY-MM-DD)
$date1 = '2020-01-01';
$date2 = '2020-05-01';
if($date2>$date1){
echo 'Date '.$date2.' is grater then '.$date1;
}
?>
The above code output will be:
Date 2020-05-01 is grater then 2020-01-01
If both dates have different format then there is a problem you can not compare both dates directly like the above code. But PHP provides you a wide range to solve this problem. You can also change the dates format first and then compare the dates like above to learn how to change the date format read How to change the date format in PHP.
Second Method:
// Compare dates with different formats.
$date1 = '2020-01-01';
$date2 = '05-01-2020';
if(strtotime($date2)>strtotime($date1)){
echo 'Date '.$date2.' is grater then '.$date1;
}
The above code output will be:
Date 05-01-2020 is grater then 2020-01-01
There is another simple way in PHP that you can use to compare two dates i.e. Datetime() a default or built-in PHP class. This method is also independent of any date format.
Third Method:
$date1 = '2020-01-01';
$date2 = '05/01/2020';
$d1 = new DateTime($date1);
$d2 = new DateTime($date2); // Can use date/string just like strtotime.
if($d2>$d1){
echo 'Date '.$date2.' is grater then '.$date1;
}
The above code output will be:
Date 05/01/2020 is grater then 2020-01-01
Now the final method is date_diff() class it is also a PHP built-in class. With this class or method, you can get a total of many objects of two dates. If the days different is negative then the second date is less then the first one.
Fourth Method:
$date1 = "2020-01-01";
$date2 = "2020-01-05";
$d1 = date_create("2020-01-01");
$d2 = date_create("2020-01-05");
$diff = date_diff($d1,$d2);
print"<prE>";
print_r($diff);
print"</pre>";
if($diff->invert=="0"){
echo 'Date '.$date2.' is grater then '.$date1;
}
//To get days
//$diff->format("%R%a days");
The above code output will be.
DateInterval Object
(
[y] => 0
[m] => 0
[d] => 4
[h] => 0
[i] => 0
[s] => 0
[weekday] => 0
[weekday_behavior] => 0
[first_last_day_of] => 0
[invert] => 0
[days] => 4
[special_type] => 0
[special_amount] => 0
[have_weekday_relative] => 0
[have_special_relative] => 0
)
Date 2020-01-05 is grater then 2020-01-01
The above method is not used commonly but has very void data. Normally the above method used to get days difference.
- 5 years ago
- Zaid Bin Khalid
- 34,733 Views
-
9