Laravel Carbon how to change timezone without changing the hour

Use the shiftTimezone() method instead of setTimezone().

If you call setTimezone() on an existing instance of Carbon,
it will change the date/time to the new timezone, for example:

$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

However, calling shiftTimezone() instead will set the
timezone without changing the time. Lets try it again from the start:

$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

Of course you can chain the methods together as well:

$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

You can also “shift” the timezone by passing the timezone as part of the
settings array:

$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

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)