问题
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
- Set the yii formatter timezone to utc
Yii::$app->formatter->timeZone = 'UTC';
before callingasDatetime
function (and set back to original if needed). - Before passing the timestamp to asTimestamp, offset it by your timezone to convert it to UTC.
- 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