Maison  >  Article  >  développement back-end  >  Comment calculer la différence horaire entre les dates en PHP ?

Comment calculer la différence horaire entre les dates en PHP ?

Susan Sarandon
Susan Sarandonoriginal
2024-10-17 19:37:02259parcourir

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>
  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>

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

Ce qui précède est le contenu détaillé de. pour plus d'informations, suivez d'autres articles connexes sur le site Web de PHP en chinois!

Déclaration:
Le contenu de cet article est volontairement contribué par les internautes et les droits d'auteur appartiennent à l'auteur original. Ce site n'assume aucune responsabilité légale correspondante. Si vous trouvez un contenu suspecté de plagiat ou de contrefaçon, veuillez contacter admin@php.cn