DateTime picker and database


I’ve a database field of datetime type.

On the form I’m trying to use the CJuiDateTimePicker extension, which provides a date in dd/mm/yyyy hh:ii format, but the database is dd/mm/yyyy hh:ii:ss. So it happens that if I enter the date in a format which is not exactly the one on the database the input is ignored.

how can I parse and format the date before the insert?


Solved by myself by adding the following into the controller

$_POST['Prepagata']['data_vendita'] = CDateTimeParser::parse ($_POST['Prepagata']['data_vendita'], 'dd-MM-yyyy HH:mm:ss');

$_POST['Prepagata']['data_vendita'] = Yii::app ()->dateFormatter->format ('yyyy-MM-dd HH:mm:ss', $_POST['Prepagata']['data_vendita']);

You can use function parse from CDateTimeParser, you see how to use this function on the documentation

lol, sorry, you posted the solution before :)

still I don’t understand how to correctly handle this.

On the form I have ‘dd/MM/yyyy HH:mm’, while on the db being a datetime field it’s a ‘yyyy-MM-dd HH:mm:ss’.

In order to allow ajax validation in the model’s rule I must set ‘dd/MM/yyyy HH:mm’, but then will fail to validate form submit!

how should I do?


I dont know why you dont put the same formats on form and on database.

But if I assume that you have different formats, you could do the following:

Be aware, i didnt test this code

public actionSaveMyDatePicker() {

 $modelObject = new MyModel();

 if(isset($_POST['MyModel'] === true) {

   $modelObject->attributes = $_POST['MyModel'];

   //here we validate the model object, to ensure that validation rules are ok (to ensure that we have dd/MM/yyyy HH:mm format) 

   if($modelObject->validate() === true) {

     //if model is validated, we transform here the date

     $modelOblect->data_vendita = CDateTimeParser::parse ($modelObject->data_vendita , 'dd-MM-yyyy HH:mm:ss');

     //we save withouth checking validation rules





Of course, if you can avoid to save without checking validation rules is better. so i suggest to you to implement the functionbeforeSave() in your model (i assume that you are using Active Records) and manage the parsing date on that function.

I hope its clear…

Because the first is the display format (for italian locale), while the database stores in the yyyy-mm-dd format.

I’l try the beforeSave option, thanks!

Well, I do not know this question has been solved or not, but would like to answer for new bee ( like me ) because was facing the same problem and hopefully able to resolved.

  1. check your database format [ in my case]

  2. set the same format in Datetime picker field.


        'options'   => array(
         'dateFormat' => '',
         'timeFormat' => 'hh:mm:ss tt',//'hh:mm tt' default

    here, yy in dateFormat = yyyy , so no worries.

And thus you can successfully save the datetime values in your database.

Glad ! ;D :rolleyes: