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.