YII:如何更改视图上显示的日期时间格式

Cal*_*lua 5 php datetime model view yii

Yii中的一个新手问题:我在Yii中有一个包含日期时间字段的表模型.

我正在使用CActiveForm来显示这个字段:

<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>
Run Code Online (Sandbox Code Playgroud)

但显示的文本字段是日期时间格式来自MySQL,即yyyy-mm-dd hh:mm:ss

如何将文本字段上显示的格式更改为其他时间格式?(也许dd/mm/yy或mm/dd/yy或者其他)

任何帮助,将不胜感激.

谢谢!

小智 26

如果您希望以一种格式存储日期,但以其他格式(即多个视图)显示,则考虑在模型中更改它.

例如:

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 ();
    }
}
Run Code Online (Sandbox Code Playgroud)

您覆盖哪些方法取决于您要实现的目标.

来自文档:

  1. 自定义CActiveRecord提供了一些占位符方法,可以在子类中重写这些方法以自定义其工作流.
    • beforeValidate和afterValidate:在执行验证之前和之后调用它们.
    • beforeSave和afterSave:在保存AR实例之前和之后调用它们.
    • beforeDelete和afterDelete:在删除AR实例之前和之后调用它们.
    • afterConstruct:为使用new运算符创建的每个AR实例调用此方法.
    • beforeFind:在使用AR查找程序执行查询(例如find(),findAll())之前调用它.
    • afterFind:在作为查询结果创建的每个AR实例之后调用.