Yii – Converting MySql dates to locale dates

It seems strange to me that two systems that have been around for so long and worked so closely together, do not manipulate dates in the same way.

It is also so easy to waste hours of time trying to manipulate dates, check that date A is less than date B and so on…

Using Events in a Yii model

The Yii model, or more accurately the CActiveRecord class, provides a number of hooks with which you can customise your workflow on database reads and updates.

Using the afterFind and beforeSave events enables you to intercept and modify data before passing it on either to User/view layer or back to the database.

PHP date class

On this basis, you can modify date formats between the two layers as follows:

        public function beforeSave()
        {
            //PHP dates are displayed as dd/mm/yyyy
            //MYSQL dates are stored as yyyy-mm-dd
            $from=DateTime::createFromFormat('d/m/Y',$this->booking_from);
            $this->booking_from=$from->format('Y-m-d');

            $to=DateTime::createFromFormat('d/m/Y',$this->booking_to);
            $this->booking_to=$to->format('Y-m-d');

            parent::beforeSave();
            return true;
        }

       public function afterFind()
        {
            //PHP dates are displayed as dd/mm/yyyy
            //MYSQL dates are stored as yyyy-mm-dd
            $from=DateTime::createFromFormat('Y-m-d',$this->booking_from);
            $this->booking_from=$from->format('d/m/Y');

            $to=DateTime::createFromFormat('Y-m-d',$this->booking_to);
            $this->booking_to=$to->format('d/m/Y');

            parent::afterFind();
            return true;
        }

You could, of course, add locale dependant formatting if required.

It is worth noting that;

i)  afterSave will leave your date in MySql format.  You will either need to force a read or convert back to PHP format with an afterSave event

ii) Your events must return true otherwise this can cause you problems such as the model->save() not working for no apparent reason.

I have wondered whether to set the model->dateField to the PHP date class and then in any views to convert using $date->format.  This would also make it much simple to do date calculations in the controller or model.

Wouldn’t it be nice if all this were handle within Yii….

Let’s Start a Project!

Contact Me