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?
$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'
// )
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;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With