【问题标题】:Parse date from mysql to carbon object and then transform into local timezone将日期从 mysql 解析为 carbon 对象,然后转换为本地时区
【发布时间】:2014-05-31 03:02:40
【问题描述】:

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

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

此日期为 UTC。如何将其作为 UTC 解析为 Carbon,然后告诉 Carbon 将时间更改为本地时区?我错过了什么吗?

【问题讨论】:

    标签: laravel laravel-4 php-carbon


    【解决方案1】:

    这是我使用的解决方案。我使用 on 函数将日期设为 UTC (toutc),并使用一个函数将其切换回本地时间 (tolocal)。在用户登录期间,我设置了会话变量“时区”。

    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;
    }
    

    【讨论】:

      【解决方案2】:
      $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'
      // )
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-10-22
        • 2014-01-28
        • 2015-12-10
        • 1970-01-01
        • 1970-01-01
        • 2021-08-16
        • 2020-09-08
        相关资源
        最近更新 更多