"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Calculate the Hour Difference between Dates in PHP?

How to Calculate the Hour Difference between Dates in PHP?

Published on 2024-11-09
Browse:301

How to Calculate the Hour Difference between Dates in PHP?

Determining the Hour Difference between Dates in PHP

You're looking to calculate the hour difference between two dates, which are formatted in "Y-m-d H:i:s."

To achieve this in PHP:

  1. Convert the Dates to Timestamps:

    Timestamps represent the number of seconds since January 1, 1970, at midnight, in your server's time zone. To convert dates to timestamps, use the strtotime() function:

    $timestamp1 = strtotime($date1);
    $timestamp2 = strtotime($date2);
  2. Calculate the Hour Difference:

    Subtract the earlier timestamp from the later timestamp and divide by 3600 to get the hour difference:

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

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

Release Statement This article is reprinted at: 1729164914 If there is any infringement, please contact [email protected] to delete it
Latest tutorial More>

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