PHP datetime->diff 计算了错误的小时数(3 太多)


php datetime->diff is calculating wrong amount of hours (3 too much)

我在php中有以下DateTime对象:

[start1] => DateTime Object ( 
    [date] => 2012-05-21 12:59:59
    [timezone_type] => 3
    [timezone] => Europe/Berlin
)
[end1] => DateTime Object ( 
    [date] => 2012-05-21 22:36:00
    [timezone_type] => 3
    [timezone] => Europe/Berlin
)

以及以下结果:

$time->end1->diff($time->start1

是:

DateInterval Object ( [y] => 0 [m] => 0 [d] => 0 [h] => 12 [i] => 36 [s] => 2 [invert] => 1 [days] => 0 )

为什么我得到的时间段是 12 小时而不是 9 小时?

我已经找到了解决方案...在做差异之前,我在 start1 对象上做了一个 sub((。现在我已经明白为什么我的结果是错误的了......这是答案,但我真的不知道为什么会发生这种情况。http://www.php.net/manual/en/datetime.sub.php#101175

我知道

这实际上可能是您创建两个 DateTime 对象的方法,但我想我会把对我有用的东西放在一起,看看它是否会帮助你。

为了创建两个对象,我做了:

$start1 = new DateTime('2012-05-21 12:59:59', new DateTimeZone('Europe/Berlin'));
$end1   = new DateTime('2012-05-21 22:36:00', new DateTimeZone('Europe/Berlin'));

并打印出两个对象和差异:

print_r($end1->diff($start1));

我得到了:

DateTime Object
(
    [date] => 2012-05-21 12:59:59
    [timezone_type] => 3
    [timezone] => Europe/Berlin
)
DateTime Object
(
    [date] => 2012-05-21 22:36:00
    [timezone_type] => 3
    [timezone] => Europe/Berlin
)
DateInterval Object
(
    [y] => 0
    [m] => 0
    [d] => 0
    [h] => 9
    [i] => 36
    [s] => 1
    [invert] => 1
    [days] => 0
)

我看到 start1 和 end1 对象的输出是相同的,但我的差异反映了正确的 9 小时差异。也许在你的PHP版本中创建DateTime对象的方式有些奇怪?