为了账号安全,请及时绑定邮箱和手机立即绑定

YII2中 ActiveForm里的field怎么可以输出时间而不是时间戳?

YII2中 ActiveForm里的field怎么可以输出时间而不是时间戳?

Yii
呼唤远方 2018-08-09 21:10:58
<?= $form->field($model, 'time')->textInput() ?>问题一:我的time在数据库里是一个时间戳,我现在想显示的是时间,怎么处理一下?问题二:我在此日期表单中填入 如 2017-05-13 的字符串,在模型中可以写什么方法将它自动转为时间戳?
查看完整描述

2 回答

?
慕雪6442864

TA贡献1812条经验 获得超5个赞

问题一:
<?=

$form->field($model, 'time')->textInput([    'value' => date("Y-m-d H:i:s", '时间戳')
])

?>

问题二:
<?php

echo @strtotime('2017-05-13');

?>


查看完整回答
反对 回复 2018-08-12
?
Qyouu

TA贡献1786条经验 获得超11个赞

class XXX extends \yii\db\ActiveRecord

{

    public function rules()

    {

        return [

        

            ...other rules...

            

            ['time', function($attr, $params) {

                if ($this->hasErrors()) return false;


                $datetime = $this->{$attr};

                

                $time = strtotime($datetime);

                // 验证时间格式是否正确

                if ($time === false) {

                    $this->addError($attr, '时间格式错误.');

                    return false;

                }

                // 将转换为时间戳后的时间赋值给time属性

                $this->{$attr} = $time;

                return true;

            }],

        ];

    }


    ...others...

    

    /**

     * 从数据库中 find() 数据后将 time 格式化。

     */

    public function afterFind()

    {

        parent::afterFind();

        $this->time = date('Y-m-d', $this->time);

    }


查看完整回答
反对 回复 2018-08-12
  • 2 回答
  • 0 关注
  • 1832 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信