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.
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))'
),
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.
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))'
),
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With