Formatos de fechas

This article is also available in the following languages:
By rikkin

Hola, soy nuevo en Bakery, les dejo un comportamiento que hice para dar vuelta la fecha, algo así como un dateformat. lo que hace es muy simple, recorre todo un array hasta las values, luego se fija en el modelo de la base de datos si el campo es un date o un datetime y luego lo da vuelta al formato que querramos. espero que les sea util. comentarios son bienvenidos.

<?php class DateformatBehavior extends ModelBehavior {

//formato que queremos. (más humano)
var $dateFormat = 'd.m.Y';
//formato de la base de datos. 
var $databaseFormat = 'Y-m-d';

function setup(&$model) {
    $this->model = $model;
}

function _changeDateFormat($date = null,$dateFormat){
    return date($dateFormat, strtotime($date));
}

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]);
            }
            //convertimos las fecha de las columnas que si queremos, las de tipo date. 
            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;
}

//antes de buscar modificamos la condicion, en el caso de que esta viaje en los conditions 
function beforeFind($model, $queryData){
    $queryData['conditions'] = $this->_changeDate($queryData['conditions'] , $this->databaseFormat);
    return $queryData;
}

//despues de buscar le decimos que la queremos en el formato que configuramos. 
function afterFind(&$model, $results){
    $results = $this->_changeDate($results, $this->dateFormat);
    return $results;
}

//antes de guardar le decimos que lo queremos en el formato de la base de datos. 
function beforeSave($model) {
    $model->data = $this->_changeDate($model->data, $this->databaseFormat);
    return true;
}

} ?>

Comments

  • Posted 02/09/12 06:46:58 PM
    Bien, de acuerdo a lo que comentó nuestro amigo en su comentario, no es la mejor forma de cambiar el formato de fechas, lo voy a seguir trabajando con el tiempo para que sea mejor. Salvo que en Cake2.0 tengamos ya definido este tema, no solo para mostrarlo, sino tambien para consultar y guardar.

    Revisando uno de mis trabajos, me di cuenta que las consultas que contenían un BETWEEN no las procesaba. Simplemente las solucioné agregando las siguientes lineas, en la funcion _changeDate ,

    function _changeDate($queryDataConditions , $dateFormat){
    foreach($queryDataConditions as $key => $value){
    if(is_array($value)){
    //nuevas lineas
    if(strstr($key,'BETWEEN')) {
    $queryDataConditions[$key][0] = $this->_changeDateFormat($queryDataConditions[$key][0],$dateFormat);
    $queryDataConditions[$key][1] = $this->_changeDateFormat($queryDataConditions[$key][1],$dateFormat);
    } else {
    $queryDataConditions[$key] = $this->_changeDate($value,$dateFormat);
    }
    } else {
    if(($value == '0000-00-00 00:00:00') || ($value == '0000-00-00')){
    $queryDataConditions[$key] = '';
    } else {
    $columns = $this->model->getColumnTypes();
    //sacamos las columnas que no queremos
    foreach($columns as $column => $type){
    if(($type != 'date') && ($type != 'datetime')) unset($columns[$column]);
    }
    //convertimos las fecha de las columnas que si queremos, las de tipo date.
    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;
    }

    de todas formas ya no me está gustando mucho este comportamiento, pero si funciona perfecto!!!. Para una primera instancia yo creo que puede resolver varios problemas en los formatos de las fechas, hasta que alguien copado nos resuelva mejor este dilema.

    Quote

  • Posted 02/03/12 09:47:00 PM
    What I did was this on my model, because doesnt work if I just copy and paste as a variable on the model. (May be I missing Something, sorry if I didnt get your idea)

    public function __construct($id=false,$table=null,$ds=null){
    parent::__construct($id,$table,$ds);
    $this->virtualFields = array(
    'dateField01' => "DATE_FORMAT({$this->alias}.dateField01, '%d.%m.%Y')",
    'dateField02' => "DATE_FORMAT({$this->alias}.dateField02, '%d.%m.%Y')"
    );
    }


    ..but I have these 2 things with this method. ...
    1) I had to do it for all the fields that are a datefields. in my code I had to put fieldDate01, dateField02 and dateFieldN to change more than one datefield. (May be with a $columns = $this->model->getColumnTypes(); and a foreach I can fix it...)

    2) Your suggestion, works only to show the datefield...(right?) because I try to make a SAVE and a FIND by and input, and doesnt work...

    Im agree with you that maybe this is not a fast way to uset... but you can Find, Save, a make a query in any format you want and with out model recursive problems. (I think... :) !! .. I dont testit 100%!!! ) ...

    Im agree with you that maybe this is not a fast way to use it... but you can Find, Save, an make a query in any format you want and without model recursive problems. (I think... :) !! .. I didnt test it 100%! ) ...

    If you have something faster I'll apreciate it. but remember that I need to find, save and make a query. ( from Hummans = d.m.y to database = Y.m.d.)

    Quote

  • Posted 01/29/12 09:32:05 AM
    Hym,

            public $virtualFields = array(
    'dateField' => "DATE_FORMAT({$this->alias}.dateField, '%Y.%m.%d')"
    );

    Not faster and better?

    Quote

Please login to post a comment.