Date validation issue.

I have a form, where the user, can use a datepicker to select a date.

The format of date can be dynamically set by the administrator therefore, i have a rule like:

public function rules()


return array(

    array('date_added', 'date', 'format'=>Yii::app()->params['systemDateFormat']),


//params['systemDateFormat'] = dd-MM-yyyy

Depending on this format, the UI date picker will get same format of date.

Now, when i submit the form, the data passes the validation and everything is okay.

The issue is that, after i validate this data, i want to save it in YYYY-mm-dd H:i:s format because the database field is a DATETIME field .

Of course, if i do something like:

$model->date_added=date('Y-m-d H:i:s', strtotime($model->date_added));


It will fail because it will validate against the rules() and the format is not correct anymore.

How can i make this right ?

Do the format conversion in the beforeSave method of your model class. Or you can write a simple behavior that implements beforeSave method, if you want to reuse the logic in multiple models.

I think the behavior is the way to go as there will be many models having same logic.

Not necessary, but do you have an example on how to do this ?

Thanks anyway for the reply :)

Not tested but can work as a starting point:

class DateNormalizer extends CActiveRecordBehavior


	public $dateAttributes;

	public function beforeSave($event)


		foreach ($this->dateAttributes as $attributeName) {

			$currentValue = $this->owner->getAttribute($attributeName);

			$normalizedValue = $this->normalize($currentValue);

			$this->owner->setAttribute($attributeName, $normalizedValue);



	protected function normalize($date)


		if ('...condition...') { // check if date needs to be formatted (e.g. with a regexp)

			$date = '...expression...'; // format the date as you need


		return $date;



In the model:

public function behaviors()


	return array(


			'class' => '',

			'dateAttributes' => array('date_added'),




Your example is perfect, i didn’t implemented it yet but i will do it as soon as possible.

Thank you for your time :)