Created
February 28, 2013 08:24
-
-
Save crisu83/5055160 to your computer and use it in GitHub Desktop.
Active record behavior for automatic formatting of date columns.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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