shortcut function for date formatting

I use this function in globals.php (as proposed in http://www.yiiframework.com/doc/cookbook/31) for quickly formatting dates:




function d($timestamp, $format=null) {

  if (!$format) {

    $format = Yii::app()->params['dateFormat'];

  }

  $a = explode('|',$format,2);

  return Yii::app()->getDateFormatter()->formatDateTime($timestamp, $a[0], isset($a[1])?$a[1]:null);

}



You can use it in your views like this:




echo d($post->createTime, 'long'); //just date with the long format


echo d($post->createTime, 'long|short'); //date and time



or just:




echo d($post->createTime);



if you define a default ‘dateFormat’ in the params section of your config file.

(the exact date formats for the ‘full’, ‘long’, ‘medium’ and ‘short’ labels are defined in the locale data files)