In Yii2, the request parameter 2025-04-04 in the interface is stored in the database as 2025-04-04 23:59:59
1. Request parameters in the interface
{
"expired_at": "2025-04-04"
}
2. The final implementation of the Rules in the model is as follows
[['expired_at'], 'datetime', 'format' => 'php:Y-m-d'],
[['expired_at'], 'filter', 'filter' => function ($value) {
return $value ? Yii::$app->formatter->asDatetime(
$value . ' 23:59:59',
'php:Y-m-d H:i:s'
) : null;
}],
$this->save(false)
3. However, the value of the last write to mysql is 2025-04-05 07:59:59
INSERT INTO convention_participant_share_recipients (share_filter_id, real_name, view, download, expired_at, id, company_id, convention_id, create_user_id, user_id, status, created_at, updated_at) VALUES ('1827082629731098', '王00713', 1, 2, '2025-04-05 07:59:59', '1827082629731120', '1826937119386040', '1826937119386049', '1826937119386043', '1827082629731108', 1, '2025-04-07 14:42:27', '2025-04-07 14:42:27')
4. yii::$app->formatter is a tool for display, not designed for the format of data storage. Decide to splicing directly, and finally achieve the following
[['expired_at'], 'datetime', 'format' => 'php:Y-m-d'],
[['expired_at'], 'filter', 'filter' => function ($value) {
return $value . ' 23:59:59';
}],
5. However, there will be a need for 2025-04-04 23:59:59 to store the database in the future, which is displayed as 2025-04-04. The final implementation is as follows
'formatter' => [
'timeZone' => 'Asia/Shanghai',
'defaultTimeZone' => 'Asia/Shanghai',
'dateFormat' => 'yyyy-MM-dd',
'datetimeFormat' => 'yyyy-MM-dd HH:mm:ss',
'timeFormat' => 'HH:mm:ss',
],
$item['expired_at'] = Yii::$app->formatter->asDate($item['expired_at'], 'php:Y-m-d');