Reputation: 495
A newbie question in Yii: I have a model of a table in Yii that contain a datetime field.
I'm using CActiveForm to display this field:
<div class="row">
<?php echo $form->labelEx($model,'createdon'); ?>
<?php echo $form->textField($model,'createdon', array('id'=>'createdon')); ?>
<?php echo $form->error($model,'createdon'); ?>
</div>
but the textfield displayed is on datetime format come from MySQL which is yyyy-mm-dd hh:mm:ss
How could I change the format displayed on the textfield to a different time format? (maybe dd/mm/yy or mm/dd/yy or else)
any help would be appreciated.
thanks!
Upvotes: 5
Views: 28177
Reputation: 41
This worked for me:
class SomeClass extends CActiveRecord
{
protected function afterFind()
{
// convert to display format
$this->my_date_time = DateTime::createFromFormat('Y-m-d H:i:s', $this->my_date_time)->format('d-m-Y');
parent::afterFind();
}
protected function beforeSave()
{
// convert to storage format
$this->my_date_time = DateTime::createFromFormat('d-m-Y', $this->my_date_time)->format('Y-m-d H:i:s');
return parent::beforeSave();
}
}
Upvotes: 3
Reputation:
If you want the date stored in one format, but displayed in another format (i.e. multiple views), then consider changing it in the model.
For example:
class Whatever extends CActiveRecord
{
protected function afterFind ()
{
// convert to display format
$this->createdon = strtotime ($this->createdon);
$this->createdon = date ('m/d/Y', $this->createdon);
parent::afterFind ();
}
protected function beforeValidate ()
{
// convert to storage format
$this->createdon = strtotime ($this->createdon);
$this->createdon = date ('Y-m-d', $this->createdon);
return parent::beforeValidate ();
}
}
Which methods you override depends on what you're trying to achieve.
- Customization CActiveRecord provides a few placeholder methods that can be overridden in child classes to customize its workflow.
- beforeValidate and afterValidate: these are invoked before and after validation is performed.
- beforeSave and afterSave: these are invoked before and after saving an AR instance.
- beforeDelete and afterDelete: these are invoked before and after an AR instance is deleted.
- afterConstruct: this is invoked for every AR instance created using the new operator.
- beforeFind: this is invoked before an AR finder is used to perform a query (e.g. find(), findAll()).
- afterFind: this is invoked after every AR instance created as a result of query.
Upvotes: 26
Reputation: 9056
All you need is to use CDateFormatter
and it's method format
OR you could use native PHP's way to format date using function date
I think there are lots of examples in PHP
manual on formatting options (as well as explanation of what each format modifier mean), so it wouldn't be a problem to figure things out, but if you have any problems with Yii's CDateFormatter
, I can give you some examples.
Upvotes: 1