您的位置:首页技术文章
文章详情页

浅谈Mybatis+mysql 存储Date类型的坑

浏览:11日期:2023-10-08 18:44:03

场景:

把一个时间字符串转成Date,存进Mysql。时间天数会比实际时间少1天,也可能是小时少了13-14小时

Mysql的时区是CST(使用语句:show VARIABLES LIKE ’%time_zone%’; 查)

先放总结:

修改方法:

1. 修改数据库时区

2. 在jdbc.url里加后缀 &serverTimezone=GMT%2B8

3. 代码里设置时区,给SimpleDateFormat.setTimeZone(...)

例外:new Date() 可以直接存为正确时间,其他的不行。比如我试过,把new Date用sdf转个2次,然后就错误了

贴一下测试的一下渣码

// 1.new Date()直接存数据库则是正确的日期 结果:√ 190626,数据库存储正常// Date now = new Date(); // 2,new Date()用simpleDateFormat转化为字符串再转为Date。结果: × 少1天 190625// Date now1 = new Date();// String tempStr = yyMMddFormatter.format(now1);// String tempStrDate = tempStr.split(' ')[0];// 会加上00:00:00// Date date = yyMMddFormatter.parse(tempStrDate); // 3.配置文件加上&serverTimezone=GMT%2B8,√ 正确 // 4. 设置中国标准时区 UTC+8 结果:√// SimpleDateFormat sdf = new SimpleDateFormat('yyMMdd'); // 设置时区: 中国标准时 China Standard Time UTC+08:00 使用GMT+8东8区,结果:?使用默认时区setTimeZone(TimeZone.getDefault);// sdf.setTimeZone(TimeZone.getTimeZone('UTC+8'));// System.out.println(sdf.getTimeZone().toString());// Date date = sdf.parse(liftMaxDt);// System.out.println(sdf.getTimeZone().toString());// System.out.println(date);//// Date targetDate = new Date(date.getTime());// System.out.println('------------------');// System.out.println(targetDate); // 5. 测试毫秒数 new Date(ms);但是要先使用sdf转入参 结果:× 问题就在于SimpleDateFormat会混乱时区// SimpleDateFormat sdf = new SimpleDateFormat('yyMMdd');// Date date = sdf.parse(liftMaxDt);// Date targetDate = new Date(date.getTime());// System.out.println('使用sdf转换date,在new Date(date.getTime())-----------');// System.out.println(targetDate); // 使用LocalDate.结果: × 还是少一天 DateTimeFormatter df = DateTimeFormatter.ofPattern('yyMMdd'); LocalDate ldt = LocalDate.parse(liftMaxDt, df); System.out.println('String类型的时间转成LocalDateTime:'+ldt); // LocalDate转LocalDateTime LocalDateTime lll = LocalDateTime.of(ldt, LocalTime.of(0,0,0)); ZoneId zone = ZoneId.systemDefault(); Instant instant = lll.atZone(zone).toInstant(); Date targetDate = Date.from(instant); // 将对象里时间属性设置为String,数据库里仍然用Date,用数据库的时间函数转化

最后,还是采用的数据库为timestamp类型,用mysql的时间函数进行转换,保证时间为数据库时间

补充知识:mybatis解决java中的date类型存入oracle数据库之后不显示时分秒

实体类中类型为java.util.Date

private Date update_date;

数据库中对应字段的类型为Date

不显示 时分秒 的情况:

Mapping文件中对应字段的jdbcType为DATE类型

如果显示时分秒的话,只需要将Mapping文件中对应字段的类型改为TIMESTAMP即可.

以上这篇浅谈Mybatis+mysql 存储Date类型的坑就是小编分享给大家的全部内容了,希望能给大家一个参考,也希望大家多多支持好吧啦网。

标签: MySQL 数据库
相关文章: