Java8新增了java.time包,提供了很多新封装好的类,使我们可以摆脱原先使用java.util.Time以及java.util.Calendar带来的复杂。
其中LocalDate正是本文中使用的可以帮助计算两个日期的间隔天数的类。(其它常用的还有LocalTime, Clock, Instant等,本文不赘述)
话不多说,上代码!
1LocalDate day0 = LocalDate.of(2014, 1, 1); 2System.out.println(day0.toString()); 3 4LocalDate day1 = LocalDate.of(2014, 1, 3); 5System.out.println(day1.toString()); 6 7System.out.println(DAYS.between(day0, day1)); 8 9System.out.println(day1.until(day0)); 10 11System.out.println(day1.until(day0, DAYS));
可以看到提供了至少三个方法来计算时间间隔天数,三个的返回值不同
2
P-2D
-2
如果是计算间隔,用
DAYS.between(day0, day1)
就可以了。
为了对比,这里奉上我之前用Calendar的方式写的计算天数。
这个是简单版本,输入的日期格式必须是“yyyy-MM-dd”,然后计算方法就是先计算中间年份的天数,再加上首尾两年不到一年的天数。
需要主意的一点是闰年的问题。
还要说明一下:为什么不用拿到时间戳的毫秒数或者秒数,然后用数值除以一天的毫秒数或者秒数来计算呢?
一是因为不想计算是否是跨天的情况。
二是纯粹练习下 java.util.Calendar和它的子类 GregorianCalendar(有个判断闰年的方法)的使用。
测试用例:
12016-02-06~2020-02-06 1461 22016-02-06~2020-03-06 1490 32016-03-06~2020-02-06 1432 42016-03-06~2020-03-06 1461 5 62016-02-06~2019-02-06 1096 72016-02-06~2019-03-06 1124 82016-03-06~2019-02-06 1067 92016-03-06~2019-03-06 1095 10 112017-02-06~2019-02-06 730 122017-02-06~2019-03-06 758 132017-03-06~2019-02-06 702 142017-03-06~2019-03-06 730 15 162017-02-06~2020-02-06 1095 172017-02-06~2020-03-06 1124 182017-03-06~2020-02-06 1067 192017-03-06~2020-03-06 1096 20 21 1 public static void main(String[] args) throws Exception { 22 2 String d1 = "2017-02-06"; 23 3 String d2 = "2020-03-06"; 24 4 calIntervalBetweenTwoDays(d1, d2); 25 5 } 26 6 27 7 public static void calIntervalBetweenTwoDays(String d1, String d2) throws Exception { 28 8 29 9 Date date1 = DATE_FORMAT.parse(d1); 3010 GregorianCalendar iCalendar = new GregorianCalendar(); 3111 iCalendar.setTime(date1); 3212 3313 GregorianCalendar jCalendar = new GregorianCalendar(); 3414 Date date2 = DATE_FORMAT.parse(d2); 3515 jCalendar.setTime(date2); 3616 3717 int betweenYears = jCalendar.get(Calendar.YEAR) - iCalendar.get(Calendar.YEAR); 3818 System.out.println("betweenYears: " + betweenYears); 3919 4020 4121 // 先计算首尾两段,然后加上中间年份的 4222 int betweenDays = (365 * (betweenYears - 1)); 4323 int iPart; 4424 boolean isLeapStart = iCalendar.isLeapYear(iCalendar.get(Calendar.YEAR)); 4525 if (isLeapStart) { 4626 iPart = 366 - iCalendar.get(Calendar.DAY_OF_YEAR); 4727 } else { 4828 iPart = 365 - iCalendar.get(Calendar.DAY_OF_YEAR); 4929 } 5030 int jPart = jCalendar.get(Calendar.DAY_OF_YEAR); 5131 betweenDays += iPart + jPart; 5232 // 修正闰年天数 5333 for (int j = 1; j < betweenYears; j++) { 5434 iCalendar.set(Calendar.YEAR, iCalendar.get(Calendar.YEAR)+1); 5535 if (iCalendar.isLeapYear(iCalendar.get(Calendar.YEAR))) { 5636 System.out.println("There is a leap year."); 5737 betweenDays++; 5838 } 5939 } 6040 6141 System.out.println("iPart: " + iPart + " ; jPart: " + jPart); 6242 System.out.println(d1 + " and " + d2 + " are " + betweenDays + " days apart."); 6343 }