You want to compare two dates và find out which one is more recent(greater).
Bạn đang xem: Datetime::diff
There are multiple ways to lớn compare two dates. In the following, you’ll find 2 methods lớn compare two dates.
Method 1: Using strtotime() function
In this way, we’ll compare two dates by two steps-Convert two dates into their respective timestamps. The timestamp of a date, as you know, is number of seconds since January 1 1970 00:00:00 UTC.Then, find out the greater date comparing those two timestamps.
The following code show how to lớn use strtotime() function khổng lồ compare two dates-
How it works:
|Line 2 -3||$date1 holds the first date & line 2 holds the second date.|
|Line 4||Using strtotime() function, we convert the first date to its equivalent timestamp.|
|Line 5||Using strtotime() function, we convert the second date to lớn its equivalent timestamp.|
|Line 6-7||In line 6, we compare if the two dates are equal. If so, then, we print it in line 7|
|Line 8-11||If two dates are not equal, then thses lines execute|
|Line 9||The ternary operator checks if $timestamp1(which is the first date) is greater than $timestamp2. If so(which is actually does), it prints the string before the colon(:), if not, it prints the next string after colon.|
Other than the yyyy-mm-dd, you can use other date format in the strtotime() function. To know which date format strtotime() function supports, please kiểm tra supported date & time formats.
Method 2: Using diff() method of DateTime class from SPL
One of the classes that SPL(Standard PHP Library) supplies is DateTime class & it has a method named diff() which can returns difference between two date objects. We’ll apply the following steps lớn compare the two dates using this method-Convert each date lớn its Date equivalent DateTime object using DateTime class.Calculate the day interval between two dates as object using diff() method.
See the following example to lớn see how the method works-
How it works:
|Line 2-3||$date1 holds the first date & line 2 holds the second date.|
|Line 4-5||Using the two dates($date1 & $date2), we create two DateTime objects ($datetimeObj1, $datetimeObj2) from the DateTime class.|
|Line 6||The diff() method will substract from $datetimeObj2 lớn $datetimeObj1 and return it as an object($interval).|
|Line 7||Here, we use format() method to lớn convert the $interval object to lớn human readable format. %R displays the sign of the difference between two dates & %a displays the total number of days. If you prints the variable $dateDiff, it will display -9.|
|Line 9-10||If two dates are same, the text in line 10 will display.|
|Line 11-13||If two dates are not equal these lines will be executed.|
|Line 12||As $dateDiff is -9, so the string after colon(:) will be displayed as output.|