I am using CTimeStampBehaviour for setting create_time and update_time resetting create_time with afterFind() in model, Basically I am setting the format of date to be displayed on the front end. But this does not work as create_time is sent 0000-00-00 00:00:00 on using model’s afterFind(). It works fine when I comment afterFind() in model.
I have seen the documentation on CTimeStampBehavior class on yii site, it has a reference to afterFind() inheritence but does not suggest how to use it. I am using afterFind() in model like this:
<?php
/**
* BNDTimezoneBehavior class file.
*
* @author Matt Skelton
* @date 25-Aug-2012
*/
/**
* Coverts database datetime fields (stored as UTC) to the user's local timezone.
*/
class BNDTimezoneBehavior extends CActiveRecordBehavior
{
public $attributes = array();
/**
* Converts the database's stored DateTime field into the user's local time.
* @param CEvent $event
*/
public function afterFind($event)
{
if (Yii::app() instanceof CWebApplication)
{
if (Yii::app()->user->getState('timezone'))
{
$timezone = Yii::app()->user->timezone;
foreach ($this->attributes as $attribute)
{
$date = $this->getOwner()->{$attribute};
$serverTimezone = new DateTimeZone("UTC");
$localTimezone = $timezone;
$date = new DateTime($date, $serverTimezone);
$date->setTimezone(new DateTimeZone($localTimezone));
$this->getOwner()->{$attribute} = $date->format('Y-m-d H:i:s');
}
}
}
}
/**
* Converts the user's local time back into UTC.
* @param CEvent $event
*/
public function beforeSave($event)
{
if (Yii::app() instanceof CWebApplication)
{
if (!$this->owner->isNewRecord)
{
if (Yii::app()->user->getState('timezone'))
{
$timezone = Yii::app()->user->timezone;
foreach ($this->attributes as $attribute)
{
$date = $this->getOwner()->{$attribute};
$serverTimezone = new DateTimeZone("UTC");
$date = new DateTime($date, new DateTimeZone($timezone));
$date->setTimezone($serverTimezone);
$this->getOwner()->{$attribute} = $date->format('Y-m-d H:i:s');
}
}
}
}
}
}
?>