php - How can the field in ActiveForm in YII2 output time instead of timestamp?
漂亮男人
漂亮男人 2017-05-16 12:57:56
0
1
534

<?= $form->field($model, 'time')->textInput() ?>

Question 1:
My time is a timestamp in the database. What I want to display now is the time. How to deal with it?

Question 2:
I fill in a string such as 2017-05-13 in this date form. What method can be written in the model to automatically convert it into a timestamp?

漂亮男人
漂亮男人

reply all(1)
刘奇
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);
    }
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template