Home > Backend Development > PHP Tutorial > How to Calculate the Difference in Hours Between Two Dates in PHP?

How to Calculate the Difference in Hours Between Two Dates in PHP?

DDD
Release: 2024-12-06 12:39:12
Original
914 people have browsed it

How to Calculate the Difference in Hours Between Two Dates in PHP?

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');
Copy after login

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;
Copy after login

Additional Resources

For further reference, explore the following documentation links:

  • [DateTime Class](https://www.php.net/manual/en/datetime.class.php)
  • [DateTimeZone Class](https://www.php.net/manual/en/datetimezone.class.php)
  • [DateInterval Class](https://www.php.net/manual/en/dateinterval.class.php)
  • [DatePeriod Class](https://www.php.net/manual/en/dateperiod.class.php)

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template