Parse date from mysql to carbon object and then transform into local timezone
Asked Answered
S

2

6

this timezone stuff is a real nightmare. I'm storing all values as UTC in my database. What I would like to do is to build a function that returns the DateTime String in the local timezone. As I'm using Laravel I would like to use Carbon for the job. I have tried multiple times now and failed.

$dateasstring= '2014-01-05 12:00:00' //retrieved from databse

This date is UTC. How do I parse it as UTC into Carbon and then tell Carbon to change the time into the localtimezone? Am I missing something?

Sides answered 16/4, 2014 at 9:59 Comment(0)
M
9
$carbon = new Carbon\Carbon($dateasstring);
$local = $carbon->timezone($localTimeZone);

// example from artisan tinker:
[1] > $utc = new Carbon\Carbon('2014-01-05 12:00:00');
// object(Carbon\Carbon)(
//   'date' => '2014-01-05 12:00:00',
//   'timezone_type' => 3,
//   'timezone' => 'UTC'
// )
[2] > $warsaw = $utc->timezone('Europe/Warsaw');
// object(Carbon\Carbon)(
//   'date' => '2014-01-05 13:00:00',
//   'timezone_type' => 3,
//   'timezone' => 'Europe/Warsaw'
// )
Medicable answered 16/4, 2014 at 10:10 Comment(0)
S
2

This is the solution I use. I use on function to make the date UTC (toutc) and one function to switch it back into local time (tolocal). During login of the user I set the session variable "timezone".

private function totimezone($utc){
    $usertz = Session::get('timezone');
    $carbon = new Carbon($utc, 'UTC');
    $carbon->timezone = new DateTimeZone($usertz);
    return $carbon;

}

private function toutc($local){
    $usertz = Session::get('timezone');
    $carbon = new Carbon($local, $usertz);
    $carbon->timezone = new DateTimeZone('UTC');
    return $carbon;
}
Sides answered 17/4, 2014 at 8:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.