微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

这篇文章主要介绍了浅谈Mybatis+MysqL 存储Date类型的坑,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

场景:

一个时间字符串转成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即可.

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐