Calculate number of hours between 2 dates in PHP

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 this case the result should be 47 hours.


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


    $t1 = StrToTime ( '2006-04-14 11:30:00' );
    $t2 = StrToTime ( '2006-04-12 12:30:00' );
    $diff = $t1 - $t2;
    $hours = $diff / ( 60 * 60 );
    

    你的答案是:

    round((strtotime($day2) - strtotime($day1))/(60*60))

    链接地址: http://www.djcxy.com/p/59012.html

    上一篇: PHP的DateTime :: Diff得到它错误?

    下一篇: 计算PHP中两个日期之间的小时数