是否有一种简便的方法可以在不更新配置文件的情况下获得UTC时间戳?
我可以使用php date_default_timezone_set
来做到这一点。
我需要在Yii2中使用它,new \DateTimeZone('UTC')
似乎不起作用。
答案 0 :(得分: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'; // ..
答案 1 :(得分:0)
通常,最方便的处理方法是使用Formatter
组件。如果所有日期都在同一时区,则可以使用配置中的Formatter::$defaultTimezone
设置仅在一个位置进行配置(您可以跳过此情况,因为UTC
是默认值):>
'formatter' => [
'defaultTimeZone' => 'UTC',
],
然后您可以使用asTimestamp()
:
echo Yii::$app->getFormatter()->asTimestamp($date);
答案 2 :(得分:0)
您可以使用以下代码在控制器操作中设置默认时区
$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();