Yii2 formatter show different date

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

Upvotes: 0

Views: 630

Answers (1)

arkoak
arkoak

Reputation: 2497

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

Upvotes: 1

Related Questions