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:
$timestamp1 = strtotime($time1);
$timestamp2 = strtotime($time2);
Calculating Hour Difference
Once we have the timestamps, we can subtract them to get the difference in seconds:
$seconds_difference = $timestamp1 - $timestamp2;
To convert this to hours, we divide by 3600, since there are 3600 seconds in an hour:
$hour_difference = round($seconds_difference / 3600, 1);
The round() function is used to avoid having a lot of decimal places.
Example Usage
Let's say we have two dates:
$time1 = "2023-05-25 15:30:15";
$time2 = "2023-05-26 09:45:30";
Using the code above:
$timestamp1 = strtotime($time1);
$timestamp2 = strtotime($time2);
$seconds_difference = $timestamp1 - $timestamp2;
$hour_difference = round($seconds_difference / 3600, 1);
echo "Hour difference: $hour_difference hours";
This would output:
Hour difference: 17.5 hours
Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.
Copyright© 2022 湘ICP备2022001581号-3