Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Laravel Carbon how to change timezone without changing the hour

I am trying to find a workaround for how I can convert the datetime stored in my Database as 'yyyy-mm-dd HH-mm-ss' and give it the timezone 'America/Los_Angeles'.

If I change the timezone, Carbon will automatically subtract 7 hours from the time, which is what happens when changing the time from UTC to PST, but the time in my DB is set for PST time. For example, I want the time to be 10am today, but it I change the timezone, Carbon will convert it to 3am today.

How can I make it where the timezone gets changed to PST but still keep the time at 10am? I need the timezone for an API call, which is why I need this figured out.

like image 721
Eric Brown Avatar asked Aug 24 '17 20:08

Eric Brown


People also ask

How do I change the time zone in Carbon laravel?

From your project root directory, open the config directory. Edit the app. php file next and the timezone value from UTC to the desired timezone from the list of available timezones.

What is the use of Carbon in laravel?

The Carbon package can help make dealing with date and time in PHP much easier and more semantic so that our code can become more readable and maintainable. Carbon is a package by Brian Nesbit that extends PHP's own DateTime class.


1 Answers

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 
like image 188
Donatello Avatar answered Sep 21 '22 01:09

Donatello