计算Java 8中两个日期之间的天数 [英] Calculate days between two dates in Java 8

查看:1940
本文介绍了计算Java 8中两个日期之间的天数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道有很多关于如何获得的问题,但我想要和使用新的Java 8 Date api的例子。我也知道JodaTime库,但我想要一种没有外部库的工作方式。

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:


  1. 防止日期保存时间错误

  2. 输入是两个Date的对象(没有时间,我知道localdatetime,但我需要处理日期实例)


推荐答案

如果您想要逻辑日历日,请使用 来自 方法api / java / time / temporal / ChronoUnit.htmlrel =noreferrer> java.time.temporal.ChronoUnit

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

如果你想要文字24小时,(持续时间),您可以使用 持续时间 而不是:

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

有关更多信息,请参阅本文档(以及其他文档:Oracle的Java 8)。

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

这篇关于计算Java 8中两个日期之间的天数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆