Skip to content

Instantly share code, notes, and snippets.

@crisu83
Created February 28, 2013 08:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save crisu83/5055160 to your computer and use it in GitHub Desktop.
Save crisu83/5055160 to your computer and use it in GitHub Desktop.
Active record behavior for automatic formatting of date columns.
<?php
class DateFormatterBehavior extends CActiveRecordBehavior {
const WIDTH_SHORT = 'short';
const WIDTH_MEDIUM = 'medium';
const WIDTH_LONG = 'long';
public $dates = array();
public function afterFind($event) {
/* @var CActiveRecord $owner */
$owner = $this->getOwner();
/* @var CDateFormatter $df */
$df = Yii::app()->getDateFormatter();
foreach ($this->dates as $attribute => $format) {
if ($owner->hasAttribute($attribute) && !empty($owner->{$attribute})) {
if (is_array($format) && count($format) === 2) {
$owner->{$attribute} = $df->formatDateTime(strtotime($owner->{$attribute}), $format[0], $format[1]);
} else {
$owner->{$attribute} = $df->format($format, strtotime($owner->{$attribute}));
}
}
}
}
public function beforeSave($event) {
/* @var CActiveRecord $owner */
$owner = $this->getOwner();
foreach ($this->dates as $attribute => $config) {
if ($owner->hasAttribute($attribute) && !empty($owner->{$attribute})) {
$owner->{$attribute} = date('Y-m-d', $this->convertDateToTimestamp($owner->{$attribute}));
}
}
}
protected function convertDateToTimestamp($date) {
if (strpos($date, '/') !== false) {
$parts = explode('/', $date);
$date = implode('-', $parts);
} else if (strpos($date, '.') !== false) {
$parts = explode('.', $date);
$date = implode('-', $parts);
}
return strtotime($date);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment