Skip to content
Advertisement

time using asTime() not correct

in my Grid view i have this to change the column time and date to use my timezone

[
    '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',
]

then in my search model i have this

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]);
    }

i also have this in my main.php components

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

in my database the created_at is saved like this 2021-11-22 11:28:16 UTC

how do i get it to show the correct time based on my timezone? (Asia/Singapore)

Advertisement

Answer

Your saved datetimes are date and time, but no reference to UTC zone. So, it’s impossible to autoformat them to Asia/Singapore datetime. Instead of that, as you know that they are UTC, and Asia/Singapore is UTC+8, you can add 8 hours to your datetimes.

So, I added code to:

  • Create a DateTime object from the created_at field value.
  • Add 8 hours to it.
  • Get new created_at value, with 8 hours added.
  • And go ahead with your original code.

Here you are:

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]);
}

And here is another (maybe better) way to convert datetime from UTC to specific time zone: UTC Date/Time String to Timezone

User contributions licensed under: CC BY-SA
2 People found this is helpful
Advertisement