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);
  • 相关阅读:
    楼宇监控说明
    数字音视频监控系统说明
    图书管理系统详细设计说明
    超邃视频远程监控系统说明
    单点登录系统(SSO)详细设计说明
    视频监控系统的作用何在
    视频监控技术与应用
    HTML--CSS样式表--基本概念(超链接的状态)
    HTML静态网页--框架
    HTML--表格与表单
  • 原文地址:https://www.cnblogs.com/Jordandan/p/11675780.html
Copyright © 2011-2022 走看看