没有不值得去解决的问题,也没有不值得去学习的技术!

Storing a Request Parameter as 2025-04-04 23:59:59 in the Database in Yii2

1. Request parameter in the API

JSON
{
"expired_at": "2025-04-04"
}

2. The final implementation in the model’s rules is as follows

PHP
[['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 ultimately written to MySQL was 2025-04-05 07:59:59

SQL
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 purposes, not designed for formatting data before saving it to the database. I decided to concatenate the string directly, and the final implementation is as follows

PHP
[['expired_at'], 'datetime', 'format' => 'php:Y-m-d'],
[['expired_at'], 'filter', 'filter' => function ($value) {
return $value . ' 23:59:59';
}],

5. Later, there was a requirement to display the database-stored value 2025-04-04 23:59:59 as 2025-04-04. The final implementation is as follows

PHP
'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');

关于作者 · 持续学习与技术实践

我是一名拥有 15 年以上开发经验的技术从业者,自 2013 年起持续运营个人技术博客,记录工作与个人项目中遇到的真实问题,以及解决问题过程中的探索、实践和思考。

除了技术写作,我也在持续开发和维护自己的独立项目,探索新技术和新工具在实际场景中的应用。我始终相信,没有不值得去解决的问题,也没有不值得去学习的技术。

如果这篇文章对你有所帮助,欢迎浏览博客中的其他文章,也欢迎交流技术经验与想法。

关于我  ·  GitHub  ·  邮件联系