首页 > 解决方案 > PHP \DateInterval 计算月数不正确

问题描述

由于 PHP 时区在项目中已更改,\DateTime::diff因此不再正确计算两个日期之间的月数。

下面是一些重现问题的示例代码:

<pre>
<?php

$tz = new \DateTimeZone('UTC');

$start = new \DateTime('2020-04-01', $tz);
$end = new \DateTime('2020-04-30', $tz);
$end->modify('+1 days');
$diff = $end->diff($start);

print "Result with UTC TimeZone:\n";
print_r($diff);

// $diff[m] == 1   and $diff[d] == 0

//---With Different Timezone (Europe/Berlin)

$tz = new \DateTimeZone('Europe/Berlin');

$start = new \DateTime('2020-04-01', $tz);
$end = new \DateTime('2020-04-30', $tz);
$end->modify('+1 days');
$diff = $end->diff($start);

print "\n\nResult with Europe/Berlin TimeZone:\n";
print_r($diff);

//---------> Returns: $diff[m] == 0   and $diff[d] == 30

//With Different Timezone and Time 00:00:00  (Europe/Berlin)

$tz = new \DateTimeZone('Europe/Berlin');

$start = new \DateTime('2020-04-01 00:00:00', $tz);
$end = new \DateTime('2020-04-30 00:00:00', $tz);
$end->modify('+1 days');
$diff = $end->diff($start);

print "\n\nResult with Europe/Berlin TimeZone and 00:00 Time:\n";
print_r($diff);

//---------> Returns: $diff[m] == 0   and $diff[d] == 30

//---With Different Timezone and Time Part and Time 10:00:00  (Europe/Berlin)

$tz = new \DateTimeZone('Europe/Berlin');

$start = new \DateTime('2020-04-01 10:00:00', $tz);
$end = new \DateTime('2020-04-30 10:00:00', $tz);
$end->modify('+1 days');
$diff = $end->diff($start);

print "\n\nResult with Europe/Berlin TimeZone and 10:00 Time:\n";
print_r($diff);

//---------> Returns: $diff[m] == 1   and $diff[d] == 0

任何想法?这是 PHP 日期库中的错误吗?

我正在使用 8.0.6。

标签: phpdatetimedateinterval

解决方案


推荐阅读