Alter the incoming variables of Active Record

Hello,

I have an entity (implemented as an Active Record) in which one of the fields (columns) is a mysql datetime.

When I set the field value:


$entity->date = '1308859993';

I have the value in unix timestamp (seconds from 1970).

Can I use mysql’s function, from_unixtime to convert the integer I have to the appropriate value?

Or do I have to do the conversion in PHP before setting the value to my $entity and forget mysql’s from_unixtime?

Thanks,

Stratos

If you don’t want to use mysql date strings as the loaded value for your attribute, and instead want to use unix timestamps (or perhaps even PHP DateTime objects!) I have found the cleanest way is to convert between the two formats using the ::beforeSave() and ::afterFind() methods of CActiveRecord.

Here is an example where I maintain a ctime (creation time) and an mtime (modified time) on my records. In the DB, they are stored as mysql datetime columns. But when in code, they are PHP DateTimes.




        /**

         * converts all DateTime objects to mysql strings and does UTC / local timezone adjustment

         */

        public function beforeSave() {

                $now = new DateTime('now', new DateTimeZone('UTC'));


                if ($this->isNewRecord) {

                        $this->ctime = $now->format(DateTime::ISO8601);

                }

                $this->mtime = $now->format(DateTime::ISO8601);

              

                return parent::beforeSave();

        }


        /**

         * converts all datetimes from UTC strings to objects in the the local timezone - database is always UTC

         */

        public function afterFind() {

                $value = new DateTime($this->ctime, new DateTimeZone('UTC'));

                $value->setTimezone(new DateTimeZone(Yii::app()->params['defaultTimezone'])); // set to America/New_York for me

                $this->ctime = $value;


                $value = new DateTime($this->mtime, new DateTimeZone('UTC'));

                $value->setTimezone(new DateTimeZone(Yii::app()->params['defaultTimezone'])); // set to America/New_York for me

                $this->mtime = $value;

        }



If you don’t want to use DateTimes, here you would use other PHP date/time functions to convert the mysql datetime to a unix timestamp and vice versa, etc. Hope this approach helps you out.

Wow,

That cover’s it completely…

Thank you.