Calculate number of hours between 2 dates in PHP

前端 未结 16 1079
轮回少年
轮回少年 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:39

    The newer PHP-Versions provide some new classes called DateTime, DateInterval, DateTimeZone and DatePeriod. The cool thing about this classes is, that it considers different timezones, leap years, leap seconds, summertime, etc. And on top of that it's very easy to use. Here's what you want with the help of this objects:

    // Create two new DateTime-objects...
    $date1 = new DateTime('2006-04-12T12:30:00');
    $date2 = new DateTime('2006-04-14T11:30:00');
    
    // The diff-methods returns a new DateInterval-object...
    $diff = $date2->diff($date1);
    
    // Call the format method on the DateInterval-object
    echo $diff->format('%a Day and %h hours');
    

    The DateInterval-object, which is returned also provides other methods than format. If you want the result in hours only, you could to something like this:

    $date1 = new DateTime('2006-04-12T12:30:00');
    $date2 = new DateTime('2006-04-14T11:30:00');
    
    $diff = $date2->diff($date1);
    
    $hours = $diff->h;
    $hours = $hours + ($diff->days*24);
    
    echo $hours;
    

    And here are the links for documentation:

    • DateTime-Class
    • DateTimeZone-Class
    • DateInterval-Class
    • DatePeriod-Class

    All these classes also offer a procedural/functional way to operate with dates. Therefore take a look at the overview: http://php.net/manual/book.datetime.php

提交回复
热议问题