phpyiitimezonecgridview

Change timezone for CGridView


I am currently working on a web application that will allow me to change the timezone during the execution. I started to test some cases, but it unfortunately doesn't work for the CGridView.

Working tests

This code here works for changing the timezone. I use the setTimeZone() function wich is a wrapper of the date_default_timezone_set() function.

Yii::app()->setTimeZone("America/Montreal");
echo "mtl:".date("Y-m-d H:i", 1396624849)."<br>";

Yii::app()->setTimeZone("Asia/Gaza");
echo "gz:".date("Y-m-d H:i", 1396624849);

The output is making a lot of sens (mtl:2014-04-04 11:20, gz:2014-04-04 18:20).

CGridView implementation

When I try the exact same line in a view with a CGridView, it doesn't work and displays only my default date format. Here is the code:

Yii::app()->setTimeZone("Asia/Gaza");
echo Yii::app()->getTimeZone();
$this->widget('zii.widgets.grid.CGridView', array(
    'id'=>'reports-grid',
    'dataProvider'=>$dataProvider,
    'filter'=>$filtersForm,
    'columns'=>array(
        array(
            'header'=>'Date',
            'name'=>'inserted',
            'type'=>'raw',
            'value'=>'date(Yii::app()->params->dateformat, strtotime($data->inserted));'
        ), 
    ),
));

The output date stays the same even if I change the time zone for America/Montreal.

What was tried so far

Adding the setTimeZone() function to a function with the date definition, as so:

'value'=>function($data){
    Yii::app()->setTimeZone("America/Montreal");
    return date(Yii::app()->params->dateformat, strtotime($data->inserted));
}

The result was the same as before.

Conclusion

Why is it not working? Is there a way to change the timezone dynamically in Yii? Is it possible that it doesn't work because the CGridView is built with eval operations?


Solution

  • Try this, it should work.

    $dateTime = new DateTime();
    $dateTime->setTimezone(new DateTimeZone('Asia/Gaza'));
    
    $this->widget('zii.widgets.grid.CGridView', array(
        'id'=>'reports-grid',
        'dataProvider'=>$dataProvider,
        'filter'=>$filtersForm,
        'columns'=>array(
            array(
                'header'=>'Date',
                'name'=>'inserted',
                'type'=>'raw',
                'value'=>function($data) use ($dateTime){
                    $dateTime->setTimestamp(strtotime($data->inserted));
                    return $dateTime->format(Yii::app()->params->dateformat);
                }
        ))
    ));
    

    By setting the timezone outsite of the function and using it inside, it should all work fine.