Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii2 save time as UTC to database but display in other timezone

Tags:

php

yii

yii2

Is there an easy way to save date & time in UTC, but when displaying dates and times to have them convert to specific timezones? I've added

'formatter'  => [
    'class' => 'yii\i18n\Formatter',
    'timeZone'        => 'America/New York',
],

To my config but everything now saves as in EST timezone in the database. I want the database to always be UTC and have control over what timezone to display when printing out the time & date in php.

Basically I wish formatter had a separate setting for controlling the format going into the database and another setting to control the format for display purposes (as users can be in different timezones).

like image 605
keeg Avatar asked Oct 29 '22 18:10

keeg


1 Answers

Are you using Yii or Yii2?

For Yii2, first set time zone for your application, for example:

$config = [
    'timeZone' => 'Europe/London',
    // other config goes here
];

Than every time you use PHP date function date will be converted in this time zone automatically. Please note that strtotime is always returning number of seconds using UTC time, this is common error.

When saving date into database you can use formatter to get date in UTC time, for example:

$model->date = Yii::$app->formatter->asTime('2014-10-06 14:41:00 UTC');

When ouputing time zone just use PHP date function, of formatter without time zone and you will get date in time zone that is set in config file. For example:

echo date("d. M. Y.", $your_date);
like image 185
Boris Savic Avatar answered Nov 10 '22 20:11

Boris Savic