zoukankan      html  css  js  c++  java
  • Date工具遇到的一个坑

        private Date contractBeginDate(){
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.DATE,1);
            calendar.set(Calendar.HOUR,0);
            calendar.set(Calendar.MINUTE,0);
            calendar.set(Calendar.SECOND,0);
            calendar.set(Calendar.MILLISECOND,0);
    //        calendar.set(Calendar.AM,0);
            return calendar.getTime();
        }
    
        private Date contractEndDate(Date beginDate){
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(beginDate);
            calendar.add(Calendar.YEAR,1);
            return calendar.getTime();
        }
    
    calendar.set(Calendar.AM,0);
    这一句会导致 代码并不是加1年 反而是减一年

    测试代码:
       @Test
        public void testEndDate(){
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date tomer = contractBeginDate();
            Date endDate = contractEndDate(tomer);
            Date yearLater = contractEndDate(new Date());
    
            System.out.println(format.format(new Date()));
            System.out.println(format.format(tomer));
            System.out.println(format.format(endDate));
            System.out.println(format.format(yearLater));
        }
    
        private Date contractEndDate(Date beginDate){
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(beginDate);
            calendar.add(Calendar.YEAR,1);
            return calendar.getTime();
        }
    
        private Date contractBeginDate(){
            Calendar calendar = Calendar.getInstance();
            calendar.setTime(new Date());
            calendar.add(Calendar.DATE,1);
            calendar.set(Calendar.HOUR,0);
            calendar.set(Calendar.MINUTE,0);
            calendar.set(Calendar.SECOND,0);
            calendar.set(Calendar.MILLISECOND,0);
            calendar.set(Calendar.AM,0);
            return calendar.getTime();
        }


    输出的结果:

    2019-10-15 09:47:49
    2019-10-16 00:00:00
    2018-10-16 00:00:00
    2020-10-15 09:47:49

    并不是预期的

    需要注意

    删除这一行 就正常预期的

    calendar.set(Calendar.AM,0);
  • 相关阅读:
    Vue 监听子组件事件
    延时队列
    AES加密
    centos7.9 iftop 工具源码安装
    angular pass get paragrams by router
    Android chrome console in PC
    powershell 运行带路径的exe
    win下 nrm ls报错
    windows10 安装 node 16 解决node-sass node-gyp报错
    位图和布隆过滤器
  • 原文地址:https://www.cnblogs.com/Jordandan/p/11675780.html
Copyright © 2011-2022 走看看