Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 799
Tino Avatar asked Apr 16 '14 09:04

Tino


Video Answer


2 Answers

$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'
// )
like image 200
Jarek Tkaczyk Avatar answered Nov 09 '22 15:11

Jarek Tkaczyk


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;
}
like image 38
Tino Avatar answered Nov 09 '22 13:11

Tino