使用该方法而不是 。shiftTimezone()
setTimezone()
如果您调用 Carbon 的现有实例,它会将日期/时间更改为新时区,例如:setTimezone()
$datetime = Carbon::createFromFormat('Y-m-d H:i:s', '2020-09-15 23:45:00');
echo $datetime->toAtomString() . "\n";
// 2020-09-15T23:45:00+00:00
$datetime->setTimezone('America/Los_Angeles');
echo $datetime . "\n";
// 2020-09-15T16:45:00-07:00
但是,呼叫将设置时区而不更改时间。让我们从头开始再试一次:shiftTimezone()
$datetime = Carbon::createFromFormat('Y-m-d H:i:s', '2020-09-15 23:45:00');
echo $datetime->toAtomString() . "\n";
// 2020-09-15T23:45:00+00:00
$datetime->shiftTimezone('America/Los_Angeles');
echo $datetime->toAtomString() . "\n";
// 2020-09-15T23:45:00-07:00
当然,您也可以将这些方法链接在一起:
$datetime = Carbon::createFromFormat('Y-m-d H:i:s', '2020-09-15 23:45:00')
->shiftTimezone('America/Los_Angeles');
echo $datetime->toAtomString() . "\n";
// 2020-09-15T23:45:00-07:00
您还可以通过将时区作为数组的一部分传递来“转移”时区:settings
$datetime = Carbon::createFromFormat('Y-m-d H:i:s', '2020-09-15 23:45:00')
->settings(['timezone' => 'America/Los_Angeles']);
echo $datetime->toAtomString() . "\n";
// 2020-09-15T23:45:00-07:00