search

Home  >  Q&A  >  body text

php - How can the field in ActiveForm in YII2 output time instead of timestamp?

<?= $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?

漂亮男人漂亮男人2847 days ago576

reply all(1)I'll reply

  • 怪我咯

    怪我咯2017-05-16 12:59:56

    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);
        }

    reply
    0
  • Cancelreply