Calculate number of hours between 2 dates in PHP

前端 未结 16 1509
轮回少年
轮回少年 2020-11-22 14:07

How do I calculate the difference between two dates in hours?

For example:

day1=2006-04-12 12:30:00
day2=2006-04-14 11:30:00

In thi

16条回答
  •  情书的邮戳
    2020-11-22 14:55

    The easiest way to get the correct number of hours between two dates (datetimes), even across daylight saving time changes, is to use the difference in Unix timestamps. Unix timestamps are seconds elapsed since 1970-01-01T00:00:00 UTC, ignoring leap seconds (this is OK because you probably don't need this precision, and because it's quite difficult to take leap seconds into account).

    The most flexible way to convert a datetime string with optional timezone information into a Unix timestamp is to construct a DateTime object (optionally with a DateTimeZone as a second argument in the constructor), and then call its getTimestamp method.

    $str1 = '2006-04-12 12:30:00'; 
    $str2 = '2006-04-14 11:30:00';
    $tz1 = new DateTimeZone('Pacific/Apia');
    $tz2 = $tz1;
    $d1 = new DateTime($str1, $tz1); // tz is optional,
    $d2 = new DateTime($str2, $tz2); // and ignored if str contains tz offset
    $delta_h = ($d2->getTimestamp() - $d1->getTimestamp()) / 3600;
    if ($rounded_result) {
       $delta_h = round ($delta_h);
    } else if ($truncated_result) {
       $delta_h = intval($delta_h);
    }
    echo "Δh: $delta_h\n";
    

提交回复
热议问题