Dateformatter
大家好!我是 Bakery 的新手,这是我的第一篇文章,希望对大家有所帮助。这是一个用于日期格式的 Behaviors,我一直想要类似的功能,但一直找不到符合我需求的。所以,现在就有了。这是一个简单的 Dateformat Behaviors。 (我用西班牙语也发布了它)
<?php class DateformatBehavior extends ModelBehavior {
//Our format
var $dateFormat = 'd.m.Y';
//datebase Format
var $databaseFormat = 'Y-m-d';
function setup(&$model) {
$this->model = $model;
}
function _changeDateFormat($date = null,$dateFormat){
return date($dateFormat, strtotime($date));
}
//This function search an array to get a date or datetime field.
function _changeDate($queryDataConditions , $dateFormat){
foreach($queryDataConditions as $key => $value){
if(is_array($value)){
$queryDataConditions[$key] = $this->_changeDate($value,$dateFormat);
} else {
$columns = $this->model->getColumnTypes();
//sacamos las columnas que no queremos
foreach($columns as $column => $type){
if(($type != 'date') && ($type != 'datetime')) unset($columns[$column]);
}
//we look for date or datetime fields on database model
foreach($columns as $column => $type){
if(strstr($key,$column)){
if($type == 'datetime') $queryDataConditions[$key] = $this->_changeDateFormat($value,$dateFormat.' H:i:s ');
if($type == 'date') $queryDataConditions[$key] = $this->_changeDateFormat($value,$dateFormat);
}
}
}
}
return $queryDataConditions;
}
function beforeFind($model, $queryData){
$queryData['conditions'] = $this->_changeDate($queryData['conditions'] , $this->databaseFormat);
return $queryData;
}
function afterFind(&$model, $results){
$results = $this->_changeDate($results, $this->dateFormat);
return $results;
}
function beforeSave($model) {
$model->data = $this->_changeDate($model->data, $this->databaseFormat);
return true;
}
} ?>