使用asTime()的时间不正确



在我的网格视图中,我可以更改列的时间和日期以使用我的时区

[
'format' => [
'class' => 'yiii18nFormatter',
'timeZone' => 'Asia/Singapore',
],
'attribute' => 'created_at',
'label' => 'Date',
'filter' => false,
'value'=> function($model, $key, $index, $column){ return Search::getDateTime($model); }, }
'format' => 'raw',
]

然后在我的搜索模型中,我有这个

public static function getDateTime($model) {
$date = Yii::$app->formatter->asDate($model->created_at);
$time = Yii::$app->formatter->asTime($model->created_at);
return Html::a($date, null, ['href' => 'javascript:void(0);', 'class' => 'btn btn-link p-0 rounded-0 tooltips', 'data-toggle' => 'tooltip', 'data-placement'=> 'bottom', 'title' => $time]);
}

我的main.php组件中也有这个

'formatter' => [
'class' => 'yiii18nFormatter',
'dateFormat' => 'php:j M Y',
'datetimeFormat' => 'php:d/m/Y h:i a',
'timeFormat' => 'php:H:i A',
'defaultTimeZone' => 'Asia/Singapore'
],

在我的数据库中,created_at是这样保存的2021-11-22 11:28:16UTC

如何让它根据我的时区显示正确的时间?(亚洲/新加坡(

您保存的日期时间是日期和时间,但没有对UTC区域的引用。因此,无法将它们自动设置为亚洲/新加坡日期时间。相反,因为您知道它们是UTC,亚洲/新加坡是UTC+8,所以您可以将8小时添加到您的日期时间中。

所以,我添加了代码到:

  • 从created_at字段值创建一个DateTime对象
  • 再加上8个小时
  • 获取新的created_at值,并添加8小时
  • 继续使用您的原始代码

给你:

public static function getDateTime($model)
{
$datetime = new DateTime($model->created_at, new DateTimeZone('UTC'));
$datetime->add(new DateInterval('PT8H'));
$created_at = $datetime->format('Y-m-d H:i:s');
$date = Yii::$app->formatter->asDate($created_at);
$time = Yii::$app->formatter->asTime($created_at);
return Html::a($date, null, ['href' => 'javascript:void(0);', 'class' => 'btn btn-link p-0 rounded-0 tooltips', 'data-toggle' => 'tooltip', 'data-placement'=> 'bottom', 'title' => $time]);
}

这里有另一种(也许更好(将日期时间从UTC转换为特定时区的方法:UTC日期/时间字符串到时区

最新更新