Calculate number of hours between 2 dates in PHP

前端 未结 16 1083
轮回少年
轮回少年 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:54
    $diff_min = ( strtotime( $day2 ) - strtotime( $day1 ) ) / 60 / 60;
    $total_time  = $diff_min;
    

    You can try this one.

    0 讨论(0)
  • 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";
    
    0 讨论(0)
  • 2020-11-22 14:58
    $day1 = "2006-04-12 12:30:00"
    $day1 = strtotime($day1);
    $day2 = "2006-04-14 11:30:00"
    $day2 = strtotime($day2);
    
    $diffHours = round(($day2 - $day1) / 3600);
    

    I guess strtotime() function accept this date format.

    0 讨论(0)
  • 2020-11-22 15:03

    First, you should create an interval object from a range of dates. By the wording used in this sentence alone, one can easily identify basic abstractions needed. There is an interval as a concept, and a couple of more ways to implement it, include the one already mentioned -- from a range of dates. Thus, an interval looks like that:

    $interval =
        new FromRange(
            new FromISO8601('2017-02-14T14:27:39+00:00'),
            new FromISO8601('2017-03-14T14:27:39+00:00')
        );
    

    FromISO8601 has the same semantics: it's a datetime object created from iso8601-formatted string, hence the name.

    When you have an interval, you can format it however you like. If you need a number of full hours, you can have

    (new TotalFullHours($interval))->value();
    

    If you want a ceiled total hours, here you go:

    (new TotalCeiledHours($interval))->value();
    

    For more about this approach and some examples, check out this entry.

    0 讨论(0)
提交回复
热议问题