java输入日期计算天数,计算Java 8中两个日期之间的天数

I know there are lots of questions on SO about how to get, but I want and example using new Java 8 Date api. I also know JodaTime library, but I want a work way without external libraries.

Function needs to complain with these restrictions:

Prevent errors from date savetime

Input are two Date's objects (without time, I know localdatetime, but I need to do with date instances)

解决方案

If you want logical calendar days, use DAYS.between() method from java.time.temporal.ChronoUnit:

LocalDate dateBefore;

LocalDate dateAfter;

long daysBetween = DAYS.between(dateBefore, dateAfter);

If you want literal 24 hour days, (a duration), you can use the Duration class instead:

LocalDate today = LocalDate.now()

LocalDate yesterday = today.minusDays(1);

// Duration oneDay = Duration.between(today, yesterday); // throws an exception

Duration.between(today.atStartOfDay(), yesterday.atStartOfDay()).toDays() // another option

For more information, refer to this document (and other documents re:Java 8 from Oracle).

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值