在 Yii2 中,将接口中的请求参数 2025-04-04 ,存入数据库中为 2025-04-04 23:59:59 的实现
1、接口中的请求参数
{ "expired_at": "2025-04-04" }
2、最终在模型中的 rules 实现如下
[['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、但是,最后写入 MySQL 的值为 2025-04-05 07:59:59
INSERT INTO <code>convention_participant_share_recipients</code> (<code>share_filter_id</code>, <code>real_name</code>, <code>view</code>, <code>download</code>, <code>expired_at</code>, <code>id</code>, <code>company_id</code>, <code>convention_id</code>, <code>create_user_id</code>, <code>user_id</code>, <code>status</code>, <code>created_at</code>, <code>updated_at</code>) 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 是 展示用的工具,不是为了数据入库的格式化而设计的。决定直接拼接,最终实现如下
[['expired_at'], 'datetime', 'format' => 'php:Y-m-d'], [['expired_at'], 'filter', 'filter' => function ($value) { return $value . ' 23:59:59'; }],
5、不过后续有将数据库存储的 2025-04-04 23:59:59,显示为 2025-04-04 的需求。最终实现如下
'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');
近期评论