Problem:
You want to calculate number of days between two dates.
Solution:
Using diff() method of DateTime class, we can calculate difference between two dates. This approach is very easy way to implement.
PHP provides Standard PHP Library(SPL) which includes some predefined classes. DateTime class is one of those classes. The following code calculates the date difference-
<?php $date1 = "2014-04-17"; $date2 = "2014-04-29"; $datetimeObj1 = new DateTime($date1); $datetimeObj2 = new DateTime($date2); $DayDiffObj = $datetimeObj1->diff($datetimeObj2); echo "Date difference is: " .$DayDiffObj->format('%R%a days'); ?>
[wpdm_file id=70]
Output:
Date difference is: +12 days
How it works:
Line 2 | $date1 holds a date |
Line 3 | $date2 holds a date |
Line 4 | Using the first date($date1), we create an object ($datetimeObj1) of the DateTime class. |
Line 5 | Similarly, using the second date($date2), we create an object ($datetimeObj2) of the DateTime class. |
Line 6 | The diff() method returns the difference between the two DateTime objects as a DateInterval object($DayDiffObj). |
Line 7 | To convert the DateInterval object($DayDiffObj) into human readable format, we use format method. Here, the formatting characters %R will display sign of the difference between two dates. The formatting characters %a will display the total number of days represented by the $DayDiffObj object which is the difference of the two dates. |