The issue with that is that the filter, sorting, etc does not operate anymore. You end up adding more code to make that work again than you would if you were using a formatter.
Further the formatter can be easily applied to other date fields without having to add a setter (a getter, a sort configuration, …) everywhere you want to format the date differently.
Finally the date format may be just the date in some cases, but date and time in other cases, yet in another case you like it to be without seconds and then you want it as text (e.g.,"on 12/12/2013 at 13:13").
As I wanted to introduce parameters in the type format provided to grid view, my formater has a different implemetation for ‘format’:
/**
* Override the default format function to allow parameters to the formatter.
*
* (non-PHPdoc)
* @see CFormatter::format()
*/
public function format($value,$type)
{
$params=null;
if(is_array($type)) {
$params=$type;
$type=$type['type'];
unset($params['type']);
}
$method='format'.$type;
if(method_exists($this,$method)) {
if($params===null) {
return $this->$method($value);
} else {
return $this->$method($value,$params);
}
} else {
throw new CException(Yii::t('yii','Unknown type "{type}".',array('{type}'=>$type)));
}
}
// Example of different localtime:
public function formatLocalDatetime($value,$params=array())
{
if (! is_numeric($value)) {
$value = strtotime($value);
}
$d='short';$t='short';
if(count($params)==2) {
$d=$params[0];
$t=$params[1];
}
return Yii::app()->localtime->formatDateTime($value,$d,$t);
}
// Implementation for formatting numbers:
/**
* (non-PHPdoc)
* @see CFormatter::formatNumber()
*/
public function formatNumber($value, $params=array()) {
$p=array($this->numberFormat['decimals'],$this->numberFormat['decimalSeparator'],$this->numberFormat['thousandSeparator']);
$c=0;
foreach($params as $i) {
$p[$c]=$i;
}
return number_format($value,$p[0],$p[1],$p[2]);
}
Yes, a bit more complex, but I can write this:
array('name'=>'the_date_time',
'type'=>array(
'type'=>'localdatetime',
'long',
'short',
),