PHP:奇怪的DateInterval长度计算

时间:2012-02-06 16:22:19

标签: php dateinterval

在玩PHP时,我对此表示反应:

<?php

$FebruaryTheFirst = \DateTime::createFromFormat('Y-m-d H:i:s', '2001-02-01 00:00:00');
$MarchTheSecond = \DateTime::createFromFormat('Y-m-d H:i:s', '2001-03-01 00:00:00');

$interval = $FebruaryTheFirst->diff($MarchTheSecond);

echo $interval->m.PHP_EOL; // Outputs 0. WTF?

$FebruaryTheFirstbis = \DateTime::createFromFormat('Y-m-d', '2001-02-01');
$MarchTheSecondbis = \DateTime::createFromFormat('Y-m-d', '2001-03-01');

$interval2 = $FebruaryTheFirstbis->diff($MarchTheSecondbis);

echo $interval2->m.PHP_EOL; // Outputs 1. WTF?

$FebruaryTheFirstter = \DateTime::createFromFormat('Y-m-d H:i:s', '2001-02-01 00:01:00');
$MarchTheSecondter = \DateTime::createFromFormat('Y-m-d H:i:s', '2001-03-02 00:01:00');

$interval3 = $FebruaryTheFirstter->diff($MarchTheSecondter);

echo $interval3->m.PHP_EOL; // Outputs 0. WTF?

$FebruaryTheFirstfour = \DateTime::createFromFormat('Y-m-d H:i:s', '2001-02-01 01:00:00');
$MarchTheSecondfour = \DateTime::createFromFormat('Y-m-d H:i:s', '2001-03-02 01:00:00');

$interval4 = $FebruaryTheFirstfour->diff($MarchTheSecondfour);

echo $interval4->m.PHP_EOL; // Outputs 1. WTF?

问题

我应该总是得到1作为输出,因为我总是计算在2月1日到3月1日之间的月份数。但如前所示,我也得到0 =&gt; WTF?

有关我的php版本的信息

PHP 5.3.8 (cli) (built: Jan 12 2012 19:12:32) Copyright (c) 1997-2011
The PHP Group Zend Engine v2.3.0, Copyright (c) 1998-2011 Zend
Technologies with Xdebug v2.1.1, Copyright (c) 2002-2011, by Derick Rethans

1 个答案:

答案 0 :(得分:3)

看起来这是PHP中的已知错误。看看bug report。解决这个问题的唯一方法,至少就目前而言,是使用UTC来消除当地时区问题。

示例:

// Get the current timezone.
$originalTimezone = @date_default_timezone_get();

// Work in UTC.
date_default_timezone_set('UTC');

// ...
$dateStart = new DateTime('2001-02-01');
$dateEnd   = new DateTime('2001-03-01');
$interval = $dateStart->diff($dateEnd);

// Reset the timezone.
if ($originalTimezone) {
    date_default_timezone_set($originalTimezone);
}