Home > Backend Development > PHP Tutorial > How to Calculate the Hour Difference between Dates in PHP?

How to Calculate the Hour Difference between Dates in PHP?

Susan Sarandon
Release: 2024-10-17 19:37:02
Original
401 people have browsed it

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:

    <code class="php">$timestamp1 = strtotime($date1);
    $timestamp2 = strtotime($date2);</code>
    Copy after login
  2. Calculate the Hour Difference:

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

    <code class="php">$hourdiff = round(($timestamp1 - $timestamp2) / 3600, 1);</code>
    Copy after login

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

The above is the detailed content of How to Calculate the Hour Difference between 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