I was wondering if someone can kindly help me on this?
The dates coming from my database are in the datetime ‘Y-m-d H:i:s’ format but in the view forms I would like them to display as ‘d-m-Y’.
I already have a method in my model that sets the created and updated times on save, it is:
public function beforeSave() {
if ($this->isNewRecord)
$this->pr_created = new CDbExpression('NOW()');
$this->pr_updated = new CDbExpression('NOW()');
return parent::beforeSave();
}
Now I have added the following method to convert those times to display in the ‘d-m-Y’ format, it is:
protected function afterFind ()
{
// convert to display format
$this->pr_updated = strtotime ($this->pr_updated);
$this->pr_updated = date ('d-m-Y', $this->pr_updated);
$this->pr_created = strtotime ($this->pr_created);
$this->pr_created = date ('d-m-Y', $this->pr_created);
parent::afterFind ();
}
The conversion seems to work fine but when updating a form it sets the created date to 01-01-1970. The updated date is ok though.
My created and updated dates are successfully being reformatted by the afterFind method but on updating the record is setting the created date back to the Unix 1970 timestamp.
For example:
I create a new record and the dates in the database are - created 2013-05-08 14:03:19, updated 2013-05-08 14:03:19
On the actual page (in the view) it displays created 08-05-2013, updated 08-05-2013
When I update the page by clicking on the save button in my form the updated date stays as 08-05-2013 but the created date changes to 01-01-1970. In the database the created field shows 0000-00-00 00:00:00.
Saving the form seems to wipe out the date? If I change the updated date to anything else and resave the form it updates the update field correctly but not the created date field.
you change date format for those fields but when you call save() this values are sent back to database in update query. if your format is not properly recognized by db (and probably it is not, because your database shows timestamps with year at the beginning) - after saving record you end up with default value which database assign when it cannot parse string value as date
so - probably you should leave your values intact and add additional getters which return timestamps formatted your way:
//after find does not any conversion
public function getMyUpdated() {
if(!empty($this->pr_updated)) {
$updated = strtotime ($this->pr_updated);
return date ('d-m-Y', $updated);
}
return null;
}
...
and then use this getter as virtual read-only attribute:
This is very good post to learn many stuffs, like how to handle the date format conflicts between the views and database data. And also redguy suggested using virtual variables, that’s very smart way to handle the conflicts if you don’t want to mess the original date in the database.