Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Yii , show different date format in cgridview

Tags:

php

yii

I had following cgridview in Yii application, I want to change date format in value,

'columns'=>array(
        array(
                'name'=>'Date',
                'header'=>'Date',
                'value'=>'$data["work_date"]'
            ),

I want to show date in format dd-mm-yyyy currently it shows as yyyy-mm-dd.

like image 360
Kiran Avatar asked Jun 15 '12 14:06

Kiran


3 Answers

Try this,

array(
    'name'=>'Date',
    'header'=>'Date',
    //'value'=>'date("d M Y",strtotime($data["work_date"]))'
    'value'=>'Yii::app()->dateFormatter->format("d MMM y",strtotime($data->date))'
),
like image 66
VibhaJ Avatar answered Nov 10 '22 15:11

VibhaJ


I guess there is more elegant way to format date (or anything else) than the one proposed in other answers. CGridView uses formatter property to specify application's component to format values. It's format by default.

So one should configure format component in application's configuration file like this:

'components' => array(
    ...
    'format' => array(
        'dateFormat' => 'd-m-Y'
    )
)

If work_date is already Unix timestamp then it's enough to describe the column in CGridView as follows:

array(
    'name' => 'work_date',
    'type' => 'date'
)

If work_date is like in the question then the column's array:

array(
    'name' => 'work_date',
    'type' => 'date',
    'value' => 'strtotime($data->work_date)'
)

If one has custom field to format that is not supported by CFormatter then it's easy to add your own type custom by extending CFormatter:

class MyFormatter extends CFormatter
{
    public function formatCustom($value)
    {
        // format $value parameter, i.e. make date conversion like in the question:
        return date("d-m-Y", strtotime($value));
    }
}

Then format component's configuration is:

'components' => array(
    ...
    'format' => array(
        'class' => 'MyFormatter'
    )
)

And the column is described like this:

array(
    'name' => 'work_date',
    'type' => 'custom'
)

This way there is no need to bother about value PHP expression each time you want to format field of the same type.

like image 5
ezze Avatar answered Nov 10 '22 15:11

ezze


There are (at least) two options:

(When using CGridView/CDetailView) you may want to format a date string (ie: mysql datetime field) instead of a timestamp. You can use this:

array(
    'name' => 'startsOn',
    'format' => 'datetime',
    'value' => 'strtotime($data->startsOn)'
),

Or use this:

array(
    'name' => 'startsOn',
    'value' => 'Yii::app()->dateFormatter->format("d MMM y", strtotime($data->startsOn))'
),
like image 2
marcovtwout Avatar answered Nov 10 '22 15:11

marcovtwout