YII:如何更改视图上显示的日期时间格式 [英] YII : How to Change datetime format displayed on the View

查看:405
本文介绍了YII:如何更改视图上显示的日期时间格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Yii中的一个新手问题:
我有一个Yii中包含datetime字段的表的模型。

A newbie question in Yii: I have a model of a table in Yii that contain a datetime field.

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

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>

但是显示的文本字段是datetime格式来自MySQL,它是yyyy-mm-dd hh:mm :ss

but the textfield displayed is on datetime format come from MySQL which is yyyy-mm-dd hh:mm:ss

如何将textfield上显示的格式更改为不同的时间格式?
(也许dd / mm / yy或mm / dd / yy或其他)

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)

任何帮助将不胜感激。

谢谢!

推荐答案

如果您希望以一种格式存储日期,但以另一种格式显示多个视图),然后考虑在模型中更改它。

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.

例如:

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.

从文档



  1. 自定义CActiveRecord提供了几个占位符方法
    可以在子类中被覆盖以自定义其工作流。


    • beforeValidate和afterValidate:执行
      验证之前和之后调用这些。

    • beforeSave和afterSave:在保存AR实例之前和之后调用

    • beforeDelete和afterDelete:
      这些在AR实例被删除之前和之后被调用。

    • afterConstruct:这是为每个AR调用的实例使用
      创建新的运算符。

    • beforeFind:在AR查找器
      用于执行查询(例如find(),findAll())之前调用。

    • afterFind:这是
      在作为查询结果创建的每个AR实例后调用。

  1. 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.


这篇关于YII:如何更改视图上显示的日期时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆