Answer the question
In order to leave comments, you need to log in
Yii2. How to store and use the date in a specific format?
Hey! Set the date format for the entire project
'formatter' => [
'dateFormat' => 'dd-mm-yyyy',
],
atabase Exception – yii\db\Exception
SQLSTATE[22007]: Invalid datetime format: 1292 Incorrect date value: '18-03-2015' for column 'lock_start' at row 1
The SQL being executed was: INSERT INTO `reservation` (`id_room`, `lock_start`, `lock_finish`, `notes`, `is_cancel`, `cleaning_day`, `group_t`) VALUES (5, '18-03-2015', '27-03-2015', '', NULL, NULL, '')
Answer the question
In order to leave comments, you need to log in
To output the date in your format use:
The asDate method will recognize a string with a date in the mysql format and return a string with a date in the format from the config.
To transfer the model to the form, you will need small dances with a tambourine:
public function actionUpdate($id)
{
$model = $this->findModel($id);
// Приводим дату к пользовательскому формату
$model->lock_start = Yii::$app->formatter->asDate($model->lock_start);
// Ставим обработчик который после успешной проверки данных в пользовательском формате вернет дату в формат для mysql
$model->on(ActiveRecord::EVENT_BEFORE_UPDATE, function () use ($model) {
$model->lock_start = \DateTime::createFromFormat('d-m-Y', $model->lock_start)->format('Y-m-d');
});
// Дальше стандартный код
if ($model->load(Yii::$app->request->post())) {
if ($model->save()) {
return $this->redirect(['index']);
}
}
return $this->render('update', [
'model' => $model,
]);
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question