Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to parse a datetime string as current default timezone using Carbon?

I have a date time string that isn't in my current timezone: 2019-08-18T10:01:02Z

I need to have a Carbon version of this string.

When I simply do: (new Carbon("2019-08-19 00:37:46"))->format('Y-m-d H:i:s');

It spits out: 2019-08-18 10:01:02

I need it to get the value 2019-08-18 06:01:02 (representative of the end-user application's set timezone).

Is there a way to do this without specifying the timezone when calling Carbon? e.g. without doing Carbon::parse($file->getClientModified())->tz('America/New_York').

For example, I know strtotime takes in to account the timezone and thus: Carbon::createFromTimestamp(strtotime($str)) will work, but I feel like there must be some internal function that can do this that I am unaware of.

Basically, I am trying to avoid calling date_default_timezone_get() or getting some configuration variable everywhere.

The timezone is set normally via date_default_timezone_set().

like image 368
Alex Avatar asked Sep 16 '25 23:09

Alex


1 Answers

You can pass a second parameter to the constructor, to specify the timezone.

E.g:

$carbon = new Carbon('2019-08-19 00:37:46', 'America/Los_Angeles');

If you want to change it application-wise, just do it during your application bootstrapping. In your application service provider you can do the basic boostrapping in the boot() method.

E.g.:

public function boot() {
     date_default_timezone_set('America/Los_Angeles');
}
like image 114
yivi Avatar answered Sep 18 '25 14:09

yivi