I want to calculate the difference in hours from two dates. This is my code:
$date_now = new DateTime(date("Y-m-d H:i:s"));
$date_db = new DateTime("2010-01-24 01:01:25");
$difference = $date_now->diff($date_db);
echo $difference->h;
The problem: the hours that are returned only correspond to the same day… So in this example, even though I use the year 2010, the hours difference never exceeds 24. How can I solve this?
Naturally, when you get the hours, it is only the hours of the current day. Otherwise that information would be useless in most contexts. Consider if you wanted to format the output as
If the h variable on the DateInterval object worked as you assumed, you could end up with an output like
So, if you want to present it only as hours, you have to sum up the hours of the days and add it to the hours of the current day, according to the documentation on the DateInterval class.