【问题标题】:Yii2 get time as UTCYii2 获取 UTC 时间
【发布时间】:2019-08-25 22:12:51
【问题描述】:

有没有一种简单的方法可以在不更新配置文件的情况下获取 UTC 时间戳?

我可以通过使用 php date_default_timezone_set 来做到这一点。 我在 Yii2 中需要这个,new \DateTimeZone('UTC') 似乎不起作用。

【问题讨论】:

    标签: php yii2 timestamp utc


    【解决方案1】:
    $date = new \DateTimeZone(\Yii::$app->timeZone);
    echo $date->getName().'<br>';
    
    
    $date = new DateTimeZone('UTC');
    echo $date->getName().'<br>'; 
    
    
    \Yii::$app->timeZone = 'EST';
    $date = new DateTimeZone(\Yii::$app->timeZone);
    echo $date->getName(); 
    

    使用 Yii 函数

    // @var string the time zone to use for formatting time and date values.
    // This can be any value that may be passed to [date_default_timezone_set()](http://www.php.net/manual/en/function.date-default-timezone-set.php)
    Yii::$app->formatter->timeZone = 'UTC';
    
    
    // @var string the default format string to be used to format a [[asDate()|date]]. `UTC`, `Europe/Berlin` or `America/Chicago`.
    Yii::$app->formatter->defaultTimeZone = 'UTC';
    // or
    $formatter= new \yii\i18n\Formatter;
    $formatter->defaultTimeZone = 'UTC'; // ..
    

    【讨论】:

      【解决方案2】:

      通常最方便的处理方式是使用Formatter 组件。如果所有日期都在同一个时区,那么您将在配置中使用 Formatter::$defaultTimezone 设置仅在一个地方进行配置(您可以跳过此设置,因为 UTC 是默认值):

      'formatter' => [
          'defaultTimeZone' => 'UTC',
      ],
      

      那么你可以使用asTimestamp():

      echo Yii::$app->getFormatter()->asTimestamp($date);
      

      【讨论】:

        【解决方案3】:

        您可以使用以下代码在控制器操作中设置默认时区

        $UTC = new DateTimeZone("UTC");
        $newTZ = new DateTimeZone("America/New_York");
        $date = new DateTime( "2011-01-01 15:00:00", $UTC );
        $date->setTimezone( $newTZ );
        echo $date->format('Y-m-d H:i:s');
        

        或在任何控制器操作中使用

        date_default_timezone_set("Asia/Bangkok");
        echo date_default_timezone_get();
        

        【讨论】:

          猜你喜欢
          • 2012-02-28
          • 2016-04-01
          • 2020-12-26
          • 2015-01-08
          • 2014-03-31
          • 2018-07-02
          • 2011-12-24
          • 2012-01-29
          相关资源
          最近更新 更多