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

Susan Sarandon
Release: 2024-10-17 19:42:03
Original
313 people have browsed it

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

Calculating Hour Difference Between Dates in PHP

When comparing two dates represented as "Y-m-d H:i:s", determining the hour difference between them is a common requirement. Here's how to achieve this in PHP:

Converting to Timestamps

The first step is to convert both dates to Unix timestamps, which represent the number of seconds since the Unix epoch (January 1, 1970 at 00:00:00 UTC). This can be done using the strtotime() function:

<code class="php">$timestamp1 = strtotime($time1);
$timestamp2 = strtotime($time2);</code>
Copy after login

Calculating Hour Difference

Once we have the timestamps, we can subtract them to get the difference in seconds:

<code class="php">$seconds_difference = $timestamp1 - $timestamp2;</code>
Copy after login

To convert this to hours, we divide by 3600, since there are 3600 seconds in an hour:

<code class="php">$hour_difference = round($seconds_difference / 3600, 1);</code>
Copy after login

The round() function is used to avoid having a lot of decimal places.

Example Usage

Let's say we have two dates:

<code class="php">$time1 = "2023-05-25 15:30:15";
$time2 = "2023-05-26 09:45:30";</code>
Copy after login

Using the code above:

<code class="php">$timestamp1 = strtotime($time1);
$timestamp2 = strtotime($time2);

$seconds_difference = $timestamp1 - $timestamp2;
$hour_difference = round($seconds_difference / 3600, 1);

echo "Hour difference: $hour_difference hours";</code>
Copy after login

This would output:

Hour difference: 17.5 hours
Copy after login

The above is the detailed content of How to Calculate the Hour Difference Between Two Dates in PHP?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!