Home >Backend Development >PHP Tutorial >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>
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>
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>
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>
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>
This would output:
Hour difference: 17.5 hours
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!