• 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);
  • 相关阅读:
    【GO】GO开发环境安装及VS Code配置
    【计算机组成原理】第一章 计算机系统概论
    oracle 12.2新特性:sqlplus history
    取消交互式创建linux用户密码
    undo表空间收缩
    如何对undo表空间大小进行设置
    查看数据库实际使用多大内存
    Oracle 12.2Cgrid脚本安装失败软件完全删除
    有关rman备份ora-27192和ora-19511错误
    数据库altert日志中的GTX提示
  • 原文地址:https://www.cnblogs.com/Jordandan/p/11675780.html
Copyright © 2020-2023  润新知