Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Issue in yii2 timezone formatter

Tags:

yii2

in php.ini timezone is UTC. system timezone is UTC. yii defaultTimeZone is UTC. But my datetime attribute gets converted to my timezone "Asia/Kolkata" before saving into db.

Eg: UTC time 12:00Hrs my input 17.30hrs what I expect in db is 12:00hrs and in view 17.30hrs But what I got in db is 17:30hrs and in view I got 23:00hrs.

web.php:

'formatter' => 
        [
            'class' => 'yii\i18n\Formatter',
            'dateFormat' => 'php:d-m-Y',
            'datetimeFormat' => 'php:d-m-Y H:i a',
            'timeFormat' => 'php:H:i A',
            'timeZone' => 'Asia/Kolkata',
        ],
like image 466
Paul P Elias Avatar asked Oct 15 '15 03:10

Paul P Elias


1 Answers

You can choose to save a specific timestamp value using a predefined format. So let's take you have defined your datetime field in the backend as an INTEGER and you want to save it as a integer. You can set the behavior like this

public function behaviors()
{
    return [
        'timestamp' => [
            'class' => TimestampBehavior::className(),
            'attributes' => [
                ActiveRecord::EVENT_BEFORE_INSERT => 'creation_time',
                ActiveRecord::EVENT_BEFORE_UPDATE => 'update_time',
            ],
            'value' => function() { return date('U'); // unix timestamp },
        ],
    ];
}

You can configure yii\i18n\formatter to control your global date formats for display for your locale. You can set something like this in your config file that you can access across

'formatter' => 
        [
            'class' => 'yii\i18n\Formatter',
            'dateFormat' => 'php:d-m-Y',
            'datetimeFormat' => 'php:d-m-Y H:i a',
            'timeFormat' => 'php:H:i A',
            'defaultTimeZone' OR 'timeZone' => 'Asia/Calcutta', //global date formats for display for your locale.
        ],

Read this Link and also refer Doc.

Hope its works.

like image 117
GAMITG Avatar answered Oct 19 '22 06:10

GAMITG