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

查看:221
本文介绍了计算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版本提供了一些名为 DateTime DateInterval DateTimeZone DatePeriod 。关于这个课程的很酷的事情是,它考虑不同的时区,闰年,闰秒,夏令时等。除此之外,它很容易使用。在这个对象的帮助下,你想要的是:

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对象还提供了除格式。如果你想在几个小时内结果,你可以这样做:

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;

以下是文档链接:

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

所有这些课程也提供了一个程序性/功能性的操作方式。因此,请查看概述: 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天全站免登陆