Determining Hours Between Two Dates in PHP
Calculating the time difference between two dates in PHP requires an effective approach to account for various factors such as time zones, leap years, and daylight saving time.
Utilizing DateTime Objects
Newer PHP versions introduce DateTime objects that simplify date calculations. Here's a comprehensive solution using these objects:
$date1 = new DateTime('2006-04-12T12:30:00'); $date2 = new DateTime('2006-04-14T11:30:00'); $diff = $date2->diff($date1); echo $diff->format('%a Day and %h hours');
Extracting Hours from DateInterval
Alternatively, to obtain the hour difference alone, follow these steps:
$date1 = new DateTime('2006-04-12T12:30:00'); $date2 = new DateTime('2006-04-14T11:30:00'); $diff = $date2->diff($date1); $hours = $diff->h; $hours = $hours + ($diff->days * 24); echo $hours;
Additional Resources
For further reference, explore the following documentation links:
The above is the detailed content of How to Calculate the Difference in Hours Between Two Dates in PHP?. For more information, please follow other related articles on the PHP Chinese website!