Help Understanding Date Issues

Hi All,

More than one issue, all date related here …

I want to display dates in the format "dd/mm/yyyy" in grid views as well as in date editors. In the model, afterFind function I have code as follows:

protected function afterFind(){

        if (isset($this->ForWeekEndingDate)) {

            $this->ForWeekEndingDate = strtotime ($this->ForWeekEndingDate);

            $this->ForWeekEndingDate = date ('d/m/Y', $this->ForWeekEndingDate);



The above works for displaying the date format in the grid.

On the update and create form, I use a datePickerRow as follows:

<?php echo $form->datePickerRow($model, 'DateReceived', array('prepend'=>'<i class="icon-calendar"></i>','options'=>array('format'=>'dd/mm/yyyy'))); ?>

The above also works, and displays the date as expected.

Two problems though …

  1. When I edit a record, the date is now being saved as NULL. It was working at some point - impossible for me to track exactly at which point! I am not setting it null anywhere, when I check it right before I am saving, it is correct. I even tried setting the format in saveAttributes … still not working.

'ForWeekEndingDate'=>date("Y-m-d H:i:s", strtotime($_POST['Form']['ForWeekEndingDate'])),

Other fields are saving correctly - using the same saveAttributes array. In fact, when I don’t use the above code I get an error stating:

The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.

  1. When a field is NULL on the database, how do I prevent the datePickerRow from showing some default (at the moment it is 1970/01/01)?

Is there a best practice I am missing? I have read quite a bit, but am not finding much luck with this issue.

I should probably say that saving the record in the first place works fine, using the same datePickerRow

Ok, first of all, I’m pretty sure you’ve got wrong timestamp from strtotime().


so check the result of

date("Y-m-d H:i:s", strtotime($this-> ForWeekEndingDate))

right before saving.

The error “The conversion of a nvarchar data type to a datetime data type resulted in an out-of-range value.” means that you’re trying to feed your SQL Server with values he don’t like. I’m not familiar with MS SQL, but I’m sure it’s way more picky in data-type conversions than MySQL.

Next, it’s probably better to use getters/setters for things like this.

Something like

public function getFormattedDate()


    return strftime('%d/%m/%Y', strtotime($this->ForWeekEndingDate));


public function setFormattedDate($date)


    if ($date && preg_match('/(\d+)\D+(\d+)\D+(\d+)/', $date, $d)) {

        $this->ForWeekEndingDate = strftime('%Y-%m-%d %H:%M', mktime(0, 0, 0, $d[2], $d[1], $d[3]));

    } else {

        $this->ForWeekEndingDate = null;



and use $model->formattedDate instead.

(you should also add it to validation rules for mass-assignment to work)

Thanks a bunch ORey … I managed to sort it with your help!