Yii2 formatter show different date

爱⌒轻易说出口 提交于 2020-02-06 06:46:05

问题


I want to view time from db and then save it to another db.table in timestamp format, but I've get different time every time I convert it:

        print_r($sub_datetime['datetime']);echo "<br>";
        $temptime = Yii::$app->formatter->asTimestamp($sub_datetime['datetime']);
        print_r($temptime);echo "<br> ";
        $temptime2 = Yii::$app->formatter->asDatetime($temptime);
        print_r($temptime2);echo "<br> ";
        $temptime3 = Yii::$app->formatter->asTimestamp($temptime2);
        print_r($temptime3);echo "<br> ";

Get:

10-5-2015 10:00
1431252000
10-5-2015 13:00
1431262800

回答1:


The Issue

asTimestamp function assumes that the date you have specified is UTC by default and gives out the UTC time value.

asDatetime function however thinks otherwise and gets the system timezone, giving you back the date with the system timezone offset.

Solution

You have a few options, any one will work

  1. Set the yii formatter timezone to utc Yii::$app->formatter->timeZone = 'UTC'; before calling asDatetime function (and set back to original if needed).
  2. Before passing the timestamp to asTimestamp, offset it by your timezone to convert it to UTC.
  3. After getting the result of asDatetime, offset it by timezone in order to convert it back to UTC


来源:https://stackoverflow.com/questions/30052237/yii2-formatter-show-different-date

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!