Search code examples
yii2yii2-model

yii2 save date format how 1970-01-01 Database


I have a problem saving the data in the database . It saves them as 1970-01-01 , invalid date . I would read them as dd-mm-yyyy and convert them to the database in yyyy-mm-dd .

my model

public function behaviors()
{
    return [
        [
            'class' => AttributeBehavior::className(),
            'attributes' => [
                attribute ['created','updated']
                ActiveRecord::EVENT_BEFORE_INSERT => ['data_arrivo','data_part'],
                ActiveRecord::EVENT_BEFORE_UPDATE => 'data_arrivo', 'data_part'
            ],
            'value' => function ($event) {
                return date('Y-m-d', strtotime($this->data_part));
            },
        ],
    ];

Any suggestions?


Solution

  • You can use beforeSave event in model file. It will get call before saving the record into the table.

     public function beforeSave($insert) {
        if($this->data_part){
          $this->data_part = Yii::$app->formatter->asDate(strtotime($this->data_part), "php:Y-m-d");
        }
        return parent::beforeSave($insert);
      }
    

    Don't work i post my code

     public function beforeSave($insert) {
        if($this->data_part){
          
     $this->data_part = Yii::$app->formatter->asDatetime(strtotime($this->data_part), "php:Y-m-d");
        
        if($this->data_arrivo)
            $this->data_arrivo = Yii::$app->formatter->asDatetime(strtotime($this->data_arrivo), "php:Y-m-d");
        
      }
      return parent::beforeSave($insert);
    }