【发布时间】:2017-08-30 15:11:55
【问题描述】:
当date_default_timezone_set() 设置的时区与 Carbon 使用的时区不同时,我遇到了 Carbon 和时区问题。
在下面的示例中,我有一个 while 循环,它添加一个月并恢复到该月的开始,直到 $end_date 大于 $current_date:
date_default_timezone_set('Australia/Brisbane');
$tz = new DateTimeZone('Australia/Brisbane');
$start_date = \Carbon\Carbon::instance(new DateTime('2019-03-01 00:00:00', $tz));
$end_date = \Carbon\Carbon::instance(new DateTime('2021-03-21 23:59:00', $tz));
$current_date = $start_date->copy();
while ($end_date->gte($current_date)) {
echo $current_date->toDateTimeString() . "\n";
$current_date->addMonth()->startOfMonth();
}
如您所见,输出是正确的。
2019-03-01 00:00:00
2019-04-01 00:00:00
2019-05-01 00:00:00
2019-06-01 00:00:00
2019-07-01 00:00:00
2019-08-01 00:00:00
2019-09-01 00:00:00
2019-10-01 00:00:00
2019-11-01 00:00:00
2019-12-01 00:00:00
2020-01-01 00:00:00
一旦我将默认时区更改为UTC,我就会得到一个无限循环。为了这个例子,我将代码调整为在 10 次循环后停止:
date_default_timezone_set('UTC'); // <---- Changed to UTC
$tz = new DateTimeZone('Australia/Brisbane');
$start_date = \Carbon\Carbon::instance(new DateTime('2019-03-01 00:00:00', $tz));
$end_date = \Carbon\Carbon::instance(new DateTime('2021-03-21 23:59:00', $tz));
$current_date = $start_date->copy();
$x = 0;
while ($end_date->gte($current_date)) {
echo $current_date->toDateTimeString() . "\n";
$current_date->addMonth()->startOfMonth();
$x++;
if ($x === 10)
break;
}
这是输出。
2019-03-01 00:00:00
2019-03-01 00:00:00
2019-03-01 00:00:00
2019-03-01 00:00:00
2019-03-01 00:00:00
2019-03-01 00:00:00
2019-03-01 00:00:00
2019-03-01 00:00:00
2019-03-01 00:00:00
2019-03-01 00:00:00
我的期望是,因为我将Australia/Brisbane 作为$start_date 和$end_date 的时区传递,所以这里应该没有任何问题。
最后,如果我重建我的代码以使用 DateTime 而不是 Carbon,我没有问题。
date_default_timezone_set('UTC');
$tz = new DateTimeZone('Australia/Brisbane');
$start_date = new DateTime('2019-03-01 00:00:00', $tz);
$end_date = new DateTime('2020-03-21 23:59:00', $tz);
$current_date = clone $start_date;
while ($current_date->getTimestamp() < $end_date->getTimestamp()) {
echo $current_date->format('Y-m-d H:i:s') . "\n";
$current_date->add(new DateInterval('P1M'));
$current_date->modify('first day of this month');
}
我是否遗漏了一些对 Carbon 处理时区至关重要的东西?
【问题讨论】:
标签: php datetime timezone php-carbon