先说现象,有一个时间写到本地数据库中的值和格式化后的值相差一秒。

上代码:

String dateStr = "2023-10-13 13:14:15:999";
try {
    SimpleDateFormat sdf1 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss:SSS");
    SimpleDateFormat sdf2 = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    Date date = sdf1.parse(dateStr);
    System.out.println("日期-带毫秒值:" + sdf1.format(date));
    System.out.println("日期-不带毫秒值:" + sdf2.format(date));

    TestBean bean = new TestBean();
    bean.setTime(date);
    // 入库
    testMapper.insert(bean);
} catch (Exception e) {
    e.printStackTrace();
}

执行日志:

日期-带毫秒值:2023-10-13 13:14:15:999
日期-不带毫秒值:2023-10-13 13:14:15
Creating a new SqlSession
SqlSession [org.apache.ibatis.session.defaults.DefaultSqlSession@21ef3d1] was not registered for synchronization because synchronization is not active
JDBC Connection [HikariProxyConnection@1544756118 wrapping com.mysql.cj.jdbc.ConnectionImpl@69d5f596] will not be managed by Spring
==>  Preparing: INSERT INTO t_test ( time ) VALUES ( ? ) 
==> Parameters: 2023-10-13 13:14:15.999(Timestamp)
<==    Updates: 1

数据库中的数据:

mysql> select * from t_test;
+----+---------------------+
| id | time                |
+----+---------------------+
|  1 | 2023-10-13 13:14:16 |
+----+---------------------+

此时发现,日期原始值为2023-10-13 13:14:15:999,使用yyyy-MM-dd HH:mm:ss格式进行格式化后的值为2023-10-13 13:14:15,入库的值却为2023-10-13 13:14:16

搜索:mybatis datetime 时间四舍五入


YOLO