解析从mysql到carbon对象的日期,然后转换为本地时区

时间:2014-04-16 09:59:31

标签: laravel laravel-4 php-carbon

这个时区的东西是一场真正的噩梦。我将所有值作为UTC存储在我的数据库中。我想要做的是构建一个在本地时区返回DateTime字符串的函数。当我使用Laravel时,我想用Carbon来完成工作。我现在已多次尝试并失败了。

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

这个日期是UTC。如何将其作为UTC解析为Carbon,然后告诉Carbon将时间更改为localtimezone?我错过了什么吗?

2 个答案:

答案 0 :(得分:6)

$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'
// )

答案 1 :(得分:2)

这是我使用的解决方案。我使用函数使日期UTC(toutc)和一个函数将其切换回本地时间(tolocal)。在用户登录期间,我将会话变量设置为“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;
}