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

13,724

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)
Share:
13,724

Related videos on Youtube

Tsuna
Author by

Tsuna

Updated on June 23, 2022

Comments

  • Tsuna
    Tsuna over 1 year

    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.

  • Tsuna
    Tsuna almost 5 years
    Just wondering, if I am not using setTimeZone I actually want to use GMT hour difference how can this be done? I am thinking if using timezone would be better or the hour