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的时间函数进行转换,保证时间为数据库时间

  • 3
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值