Format Timezone for Carbon Date
Asked Answered
H

3

52

I'm trying to set the timezone for a date in a Carbon object. It works fine locally but on my production box it keeps giving me Bad timezone error.

I've tried:

$date->setTimezone('7');
$date->setTimezone('+7');
$date->setTimezone('7:00');
$date->setTimezone('+7:00');
$date->setTimezone('UTC 7');
$date->setTimezone('UTC +7');
$date->setTimezone('UTC 7:00');
$date->setTimezone('UTC +7:00');

No idea why it's complaining on my production box. Can't find documentation either on what is the "proper" format to enter here. Can someone please help.

FYI: local is windows, and prod is Ubuntu box.

Handspring answered 19/2, 2015 at 6:57 Comment(2)
is it the same as the question here?Chary
$d = Carbon::now()->setTimezone(request_timezone()); This line: 1 it won't change timestamp (aka $d->getTimestamp(); is the same as $d2 = Carbon::now(); $d2->getTimestamp();) 2 it works as it sets the timezone so that it can return the correct startOfDay() timestamp in that timezone aka YOUR_TZ 00:00's timestamp. (when not setting timezone and calls startOfDay(), it returns UTC 00:00's timestamp)Fontes
H
85

You can change the timezone with this:

$timestamp = '2014-02-06 16:34:00';
$date = Carbon::createFromFormat('Y-m-d H:i:s', $timestamp, 'Europe/Stockholm');
$date->setTimezone('UTC');

this format working fine to my Local(Ubuntu) and prod(Redhat) project.

Hattie answered 19/2, 2015 at 9:21 Comment(5)
I was stuck because I tried to set timezone with createFromTimestamp, even if it accepts second param. Apparently, Timestamp is always in UTC...Pyrethrin
@mladen-janjetović can you show me your code, how you trying?Hattie
if you want to change application wise format, you should setup config/app.timezone component as per your requirement.Hattie
something like this if i remember well $date = Carbon::createFromTimestamp($timestamp, 'EST'); It is not returning right time when call ->timezone('UTC') on this. app.timezone is set to UTC. With this createFromFormat it works well.Pyrethrin
Would Carbon take Daylight savings time into account?Pallaten
T
19

I think you should refer to the official php timezone list. In your case you can use

$date->setTimezone('Asia/Phnom_Penh');

for UTC+7:00.

Tatro answered 19/2, 2015 at 9:48 Comment(0)
B
14

For people wondering, you can chain the timezone like so:

Carbon::now()->timezone('Europe/Stockholm')
Boddie answered 19/8, 2020 at 8:50 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.