Different Format In Db And In Html Input Field

I have a MySQL database with date field in format like "2013-04-05".

I also have CActiveForm with datapicker which accepts values like "05/10/2013".

What is the proper way to convert between these formats when loading and when submitting the form?

how dose the datepicker return date and time? is there any parameter that determine date format with it?

It does not matter that it is done with datepicker. The only important thing is that I need to convert between different formats (one format in the DB and another in HTML).

Which method do I need to override to do format conversion?

I think you should use php date function:




$db_date = '2013-04-05';


$date_to_html_format = date('d/m/Y', strtotime($db_date));




AND




$date_to_html_format = '05/10/2013';


$db_date = date('Y-m-d', strtotime($db_date));



The question is not how to do this, but WHERE (in which method) to do this?

hi,

can you try this…

$tmpuser_expdate = date(‘Y-m-d’, CDateTimeParser::parse($_POST[‘User’][‘umt_tmpuser_expdate’], ‘m-d-y’));

You can do that in view file and controller class and also in model class:

In View file:




...

$date_to_html_format = '';

if($model->some_date_field!==NULL)

$date_to_html_format = date('d/m/Y', strtotime($model->some_date_field));

echo '<input type="text" name="date_input" value="$date_to_html_format">';

...



Then Catch POST data in controller class:




...

$model = new SomeModelClass('some_scenario_here_if_any');

if(isset($_POST['SomeModelClass']) and count($_POST['SomeModelClass'])>0) {

	$model->attributes = $_POST['SomeModelClass'];

	// First you can change your date format here after checking submitted date is a real date or add validation rule to model class to validate value

	$model->some_date_field = date('Y-m-d', strtotime($model->some_date_field));

	if($model->save()) {

    	// DONE

	}

}

...



Alternatively you can parse date to DB format in model class function afterValidate() by overriding…




class SomeModelClass extends CActiveRecord() {

	...

	public function afterValidate() {

    	$this->some_date_field = date('Y-m-d', strtotime($this->some_date_field));

    	return parent::afterValidate();

	}

	...

}



Note if you use afterValidate() then date parsing in controller class is not required:

Remove below line if using afterValidate()




...

$model->some_date_field = date('Y-m-d', strtotime($model->some_date_field));

...



I’ll make this in the controller

In dependent on you, if you decide to use them in controller, voew or model, even if in an extension or any extra component class.