首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >Yii2 -以不同格式保存和显示DateTime

Yii2 -以不同格式保存和显示DateTime
EN

Stack Overflow用户
提问于 2018-10-18 05:25:52
回答 3查看 1.6K关注 0票数 0

我需要保存属性"created_at“在MySQL格式"yyyy-mm-dd hh:mm:ss",但显示在php格式"d-m-Y”。

它在create scenario中运行良好,但当我更新任何属性并保存时,它会覆盖"created_at“,并在数据库中自动设置为"0000-00-00 00:00:00”。我在模型beforeValidade()afterFind()中使用了两个函数。

common\models\Oficios.php

public function beforeValidate()
{
    if ($this->scenario == self::SCENARIO_CREATE){
        $this->created_at = date('Y-m-d H:i:s');
    }else {
        $this->created_at = $this->created_at;
    }

    return parent::beforeValidate(); 
}

public function afterFind ()
{
    // convert to display format
    $this->created_at = strtotime ($this->created_at);
    $this->created_at = date ('d-m-Y', $this->created_at);

    parent::afterFind ();
}
EN

回答 3

Stack Overflow用户

发布于 2018-10-18 05:48:23

你可以试试这个:

public function rules()
{
    return array(
        ...
        array('created_at','default',
              'value'=>date('Y-m-d H:i:s'),
              'setOnEmpty'=>false,'on'=>'insert')
    );
}

并去掉函数"beforeValidate“

我希望它能对你有所帮助。

票数 0
EN

Stack Overflow用户

发布于 2018-10-19 17:11:18

你总是可以使用行为。这是一种更加干净和先进的方式。您可以控制该模型具有的所有事件。下面是一个例子:

public function behaviors()
    {
        return [
            [
                'class' => TimestampBehavior::class,
                'createdAtAttribute' => 'created_at',
                'updatedAtAttribute' => 'created_at',
                'value' => date('Y-m-d H:i:s')
            ],
            [
                'class' => AttributeBehavior::class,
                'attributes' => [
                    ActiveRecord::EVENT_AFTER_FIND => 'created_at'
                ],
                'value' => function ($model) {
                    // Any Format you want
                    return date('d-m-Y', strtotime($model->created_at));
                }
            ]
        ];
    }
票数 0
EN

Stack Overflow用户

发布于 2018-10-23 17:21:50

如果像使用Yii::$app->formatter->asDate($model->created_at,'d-m-Y')一样将created_at保存为Unix

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52863844

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档