用PHP计算两个日期之间的小时数 [英] Calculate number of hours between 2 dates in PHP

查看:49
本文介绍了用PHP计算两个日期之间的小时数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何计算两个日期之间的时差?

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

例如:

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

在这种情况下,结果应该是 47 小时.

In this case the result should be 47 hours.

推荐答案

较新的 PHP 版本提供了一些新的类,称为 DateTimeDateIntervalDateTimeZoneDatePeriod.这个类很酷的一点是,它考虑了不同的时区、闰年、闰秒、夏令时等.除此之外,它非常易于使用.在此对象的帮助下,这是您想要的:

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');

返回的DateInterval-object 还提供了除format 之外的其他方法.如果你只想要几个小时的结果,你可以这样:

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;

这里是文档的链接:

所有这些类还提供了一种操作日期的程序/功能方式.因此,看看概述:http://php.net/manual/book.datetime.php

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

这篇关于用PHP计算两个日期之间的小时数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆