美文网首页
Calendar计算出一个月后1天的23点59分59秒,但是减1

Calendar计算出一个月后1天的23点59分59秒,但是减1

作者: 王月亮17 | 来源:发表于2022-08-20 10:16 被阅读0次

    昨天遇到的一个问题,要根据当前时间计算出一个月后的某一天,推后一天的23点59分59秒,在测试类进行测试的时候没有任何问题,代码如下:

        public Date getTheLastTime(Date date){
            Calendar calendar = Calendar. getInstance();
            calendar.setTime(date);
            calendar.set(Calendar. HOUR_OF_DAY, 0);
            calendar.set(Calendar. MINUTE, 0);
            calendar.set(Calendar. SECOND, 0);
            calendar.set(Calendar. MILLISECOND, -1);
            calendar.add(Calendar. DAY_OF_MONTH, 1);
            return calendar.getTime();
        }
    
        @Test
        public void monthLaterTest(){
            long nowTime = System.currentTimeMillis();
            long day2Sss = 30L * 24 * 60 * 60 *1000;
            long newTime = nowTime + day2Sss;
            System.out.println(getTheLastTime(time2Date(newTime)));
        }
    

    举例来说今天是 2018-6-29 11:41:52,我需要生成的时间就是 2018-7-30 23:59:59,测试类结果如下:

    Mon Jul 30 23:59:59 CST 2018
    
    image.gif

    没有任何问题,但是部到项目中执行,存入数据库的结果却成了 2018-7-31 0:00:00。

    这是因为MySQL默认存储datetime是精确到秒的,所以减掉一个毫秒之后存入MySQL,MySQL并不care。

    于是将减1毫秒改成减1秒,就好了:

    public Date getTheLastTime(Date date){
            Calendar calendar = Calendar. getInstance();
            calendar.setTime(date);
            calendar.set(Calendar. HOUR_OF_DAY, 0);
            calendar.set(Calendar. MINUTE, 0);
            calendar.set(Calendar. SECOND, -1);
            calendar.set(Calendar. MILLISECOND, 0);
            calendar.add(Calendar. DAY_OF_MONTH, 1);
            return calendar.getTime();
        }
    

    如果想让MySQL精确到毫秒,可以将数据库中的时间字段类型长度设置为3。

    相关文章

      网友评论

          本文标题:Calendar计算出一个月后1天的23点59分59秒,但是减1

          本文链接:https://www.haomeiwen.com/subject/jfjvbrtx.html