java时间戳间隔天数_Java8 LocalDate计算两个日期的间隔天数

Java8新增了java.time包,提供了很多新封装好的类,使我们可以摆脱原先使用java.util.Time以及java.util.Calendar带来的复杂。

其中LocalDate正是本文中使用的可以帮助计算两个日期的间隔天数的类。(其它常用的还有LocalTime, Clock, Instant等,本文不赘述)

话不多说,上代码!

LocalDate day0 = LocalDate.of(2014, 1, 1);

System.out.println(day0.toString());

LocalDate day1= LocalDate.of(2014, 1, 3);

System.out.println(day1.toString());

System.out.println(DAYS.between(day0, day1));

System.out.println(day1.until(day0));

System.out.println(day1.until(day0, DAYS));

可以看到提供了至少三个方法来计算时间间隔天数,三个的返回值不同

2

P-2D

-2

如果是计算间隔,用

DAYS.between(day0, day1)

就可以了。

为了对比,这里奉上我之前用Calendar的方式写的计算天数。

这个是简单版本,输入的日期格式必须是“yyyy-MM-dd”,然后计算方法就是先计算中间年份的天数,再加上首尾两年不到一年的天数。

需要主意的一点是闰年的问题。

还要说明一下:为什么不用拿到时间戳的毫秒数或者秒数,然后用数值除以一天的毫秒数或者秒数来计算呢?

一是因为不想计算是否是跨天的情况。

二是纯粹练习下 java.util.Calendar和它的子类 GregorianCalendar(有个判断闰年的方法)的使用。

测试用例:

2016-02-06~2020-02-06 1461

2016-02-06~2020-03-061490

2016-03-06~2020-02-061432

2016-03-06~2020-03-061461

2016-02-06~2019-02-061096

2016-02-06~2019-03-061124

2016-03-06~2019-02-061067

2016-03-06~2019-03-061095

2017-02-06~2019-02-06730

2017-02-06~2019-03-06758

2017-03-06~2019-02-06702

2017-03-06~2019-03-06730

2017-02-06~2020-02-061095

2017-02-06~2020-03-061124

2017-03-06~2020-02-061067

2017-03-06~2020-03-061096

1 public static void main(String[] args) throwsException {2 String d1 = "2017-02-06";3 String d2 = "2020-03-06";4 calIntervalBetweenTwoDays(d1, d2);5 }6

7 public static void calIntervalBetweenTwoDays(String d1, String d2) throwsException {8

9 Date date1 =DATE_FORMAT.parse(d1);10 GregorianCalendar iCalendar = newGregorianCalendar();11 iCalendar.setTime(date1);12

13 GregorianCalendar jCalendar = newGregorianCalendar();14 Date date2 =DATE_FORMAT.parse(d2);15 jCalendar.setTime(date2);16

17 int betweenYears = jCalendar.get(Calendar.YEAR) -iCalendar.get(Calendar.YEAR);18 System.out.println("betweenYears: " +betweenYears);19

20

21 //先计算首尾两段,然后加上中间年份的

22 int betweenDays = (365 * (betweenYears - 1));23 intiPart;24 boolean isLeapStart =iCalendar.isLeapYear(iCalendar.get(Calendar.YEAR));25 if(isLeapStart) {26 iPart = 366 -iCalendar.get(Calendar.DAY_OF_YEAR);27 } else{28 iPart = 365 -iCalendar.get(Calendar.DAY_OF_YEAR);29 }30 int jPart =jCalendar.get(Calendar.DAY_OF_YEAR);31 betweenDays += iPart +jPart;32 //修正闰年天数

33 for (int j = 1; j < betweenYears; j++) {34 iCalendar.set(Calendar.YEAR, iCalendar.get(Calendar.YEAR)+1);35 if(iCalendar.isLeapYear(iCalendar.get(Calendar.YEAR))) {36 System.out.println("There is a leap year.");37 betweenDays++;38 }39 }40

41 System.out.println("iPart: " + iPart + " ; jPart: " +jPart);42 System.out.println(d1 + " and " + d2 + " are " + betweenDays + " days apart.");43 }

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值