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


            return true;

       public function afterFind()
            //PHP dates are displayed as dd/mm/yyyy
            //MYSQL dates are stored as yyyy-mm-dd


            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....

Did you know you can hire me?

I take on projects of all sizes. From Consulting to large Development Projects.

If you're starting a new Yii project and would like some help to get setup and running or you need some help with a particular module or you just need someone to develop the whole dang thing, then just ask ...


  • chris

    Hi Jerilyn

    Thank you for your kind comments.


  • jerilynfincher

    Can I simply just say what a relief to discover somebody who genuinely understands what they're discussing on the web. You actually realize how to bring an issue to light and make it important. A lot more people really need to look at this and understand this side of your story. It's surprising you are not more popular given that you certainly possess the


Leave a Comment

twitterfacebookgooglelinkedin https://me.yahoo.com