This behavior can be attached to ActiveRecord model for automatically conversion MySQL date and datetime field to PHP5 DateTime object.
Tested with: ¶
- PHP 5.3.13
- MySQL 5.5.24
- Yii 1.1.10.r3566
Requirements ¶
- >= PHP 5.2.0
Installation ¶
Extract the release file and put it under protected/extensions.
In your ActiveRecord model, add the following code:
public function behaviors()
{
return array('edatetimebehavior' => array('class' => 'ext.EDateTimeBehavior'));
}
You may have to change 'ext.EDateTimeBehavior' if you don't put the file to 'protected/extensions'.
Usage ¶
Nothing much, now your date/datetime attributes can be used as a PHP5 DateTime object.
Enjoy the convenience.
Inspired from i18n-datetime-behavior
This is my first extension, any comments are welcome :)
Does it automatically convert back?
So I will be able to use php date() to change the display format?
Had to modify it this way when using string types
class EDateTimeBehavior extends CActiveRecordBehavior { private $mySqlDateFormat = 'Y-m-d'; private $myDateFormat = 'm/d/Y'; public function afterFind($event) { foreach($event->sender->tableSchema->columns as $columnName => $column){ if (($column->dbType != 'date')) continue; if (!strlen($event->sender->$columnName)){ $event->sender->$columnName = null; continue; } $format=DateTime::createFromFormat($this->mySqlDateFormat,$event->sender->$columnName); $event->sender->$columnName=$format->format($this->myDateFormat); } } public function beforeSave($event) { foreach($event->sender->tableSchema->columns as $columnName => $column){ if (($column->dbType != 'date')) continue; if (!strlen($event->sender->$columnName)){ $event->sender->$columnName = null; continue; } if (($column->dbType == 'date')) { $format=DateTime::createFromFormat($this->myDateFormat,$event->sender->$columnName); $sqlDate = $format->format($this->mySqlDateFormat); $event->sender->$columnName = $sqlDate; } } } }
You should not initialize with timestamp
Hi
I think you should not initialized DateTime with "@timestamp".
From php.net:
The $timezone parameter and the current timezone are ignored when the $time parameter either is a UNIX timestamp (e.g. @946684800) or specifies a timezone (e.g. 2010-01-28T15:00:00+02:00).
DateTime.setTimezone(946684800) should work. Or:
If you have any questions, please ask in the forum instead.
Signup or Login in order to comment.