Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using carbon to change utc to other timezone gives the same result

In my db, the time is saved as utc.

I am trying to use carbon (doesn't have to be carbon) and change it to other timezone such as pacific timezone or America/Vancouver when passing data to the front end. I want to keep the db having utc which would be more flexible in the future.

But somehow I am getting the same result when I used carbon

$tz = $tt->created_at;  // "2019-01-16 18:21:31"
$date = Carbon::createFromFormat('Y-m-d H:i:s', $tz, 'America/Vancouver');
dd($tz, $date);

$date gives me the result of

Carbon @1547691691 {#212
  date: 2019-01-16 18:21:31.0 America/Vancouver (-08:00)
}

when I do dd($tz, $date->toDateTimeString());

I get

"2019-01-16 18:21:31"  // $tz
"2019-01-16 18:21:31"  // $date->toDateTimeString()

shouldn't $date->toDateTimeString() be "2019-01-16 10:21:31" because the time is -08:00?

Can someone please give me a hand on what I have done wrong here?

Thanks in advance.

like image 772
Tsuna Avatar asked Jan 16 '19 20:01

Tsuna


1 Answers

When you use createFromFormat you are creating a Carbon Object as you can read in the documentation with 2019-01-16 18:21:31 DateTime in America/Vancouver timezone

But what you actually want to do is converting your UTC time to America/Vancouver time.

You should create DateTime with UTC Timezone

$tz = $tt->created_at;  // "2019-01-16 18:21:31" (UTC Time)
$date = Carbon::createFromFormat('Y-m-d H:i:s', $tz, 'UTC');

So your DateTime Object is in UTC like your Database and then convert it to America/Vancouver time

$date->setTimezone('America/Vancouver'); // "2019-01-16 10:21:31" (America/Vancouver Time)
like image 133
M4HdYaR Avatar answered Nov 15 '22 19:11

M4HdYaR