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);