[英]Calculate days between two Dates in Java 8
I know there are lots of questions on SO about how to get Date
s in Java, but I want an example using new Java 8 Date
API.我知道关于如何在 Java 中获取
Date
有很多问题,但我想要一个使用新 Java 8 Date
API 的示例。 I also know about the JodaTime library, but I want a method without relying on external libraries.我也知道 JodaTime 库,但我想要一种不依赖外部库的方法。
The function needs to be compliant with these restrictions:该功能需要符合以下限制:
Date
objects (without time, I know about LocalDateTime
, but I need to do this with Date
instances)Date
对象(没有时间,我知道LocalDateTime
,但我需要用Date
实例来做到这一点)If you want logical calendar days , use DAYS.between()
method from java.time.temporal.ChronoUnit
:如果你想逻辑日历天,使用
DAYS.between()
从方法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:如果您想要文字 24 小时天,(持续时间),您可以使用
Duration
类:
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 .有关更多信息,请参阅此文档。
根据 VGR 的评论,您可以使用以下内容:
ChronoUnit.DAYS.between(firstDate, secondDate)
You can use until()
:您可以使用
until()
:
LocalDate independenceDay = LocalDate.of(2014, Month.JULY, 4);
LocalDate christmas = LocalDate.of(2014, Month.DECEMBER, 25);
System.out.println("Until christmas: " + independenceDay.until(christmas));
System.out.println("Until christmas (with crono): " + independenceDay.until(christmas, ChronoUnit.DAYS));
Output:输出:
Until christmas: P5M21D
Until christmas (with crono): 174
as mentioned at comment - first untill()
returnsPeriod .正如评论中提到的 - 首先
untill()
返回Period 。
Snippet from the documentation:来自文档的片段:
A date-based amount of time in the ISO-8601 calendar system, such as '2 years, 3 months and 4 days'.
ISO-8601 日历系统中基于日期的时间量,例如“2 年、3 个月和 4 天”。
This class models a quantity or amount of time in terms of years, months, and days.此类以年、月和日为单位对数量或时间进行建模。 See Duration for the time-based equivalent to this class.
请参阅 Duration 以了解与此类的基于时间的等效项。
If startDate and endDate are instance of java.util.Date
如果startDate和endDate是java.util.Date 的实例
We can use the between( ) method from ChronoUnit enum:我们可以使用ChronoUnit枚举中的between()方法:
public long between(Temporal temporal1Inclusive, Temporal temporal2Exclusive) {
//..
}
ChronoUnit.DAYS count days which completed 24 hours . ChronoUnit.DAYS计算完成 24 小时的天数。
import java.time.temporal.ChronoUnit;
ChronoUnit.DAYS.between(startDate.toInstant(), endDate.toInstant());
//OR
ChronoUnit.DAYS.between(Instant.ofEpochMilli(startDate.getTime()), Instant.ofEpochMilli(endDate.getTime()));
You can use DAYS.between
from java.time.temporal.ChronoUnit
您可以使用
DAYS.between
的java.time.temporal.ChronoUnit
eg例如
import java.time.temporal.ChronoUnit;
...
long totalDaysBetween(LocalDate dateBefore, LocalDate dateAfter) {
return DAYS.between(dateBefore, dateAfter);
Use the DAYS in enum java.time.temporal.ChronoUnit .在枚举java.time.temporal.ChronoUnit 中使用 DAYS。 Below is the Sample Code :
以下是示例代码:
Output : *Number of days between the start date : 2015-03-01 and end date : 2016-03-03 is ==> 368. **Number of days between the start date : 2016-03-03 and end date : 2015-03-01 is ==> -368*输出: *开始日期:2015-03-01 和结束日期:2016-03-03 之间的天数 ==> 368。**开始日期:2016-03-03 和结束日期之间的天数: 2015-03-01 是 ==> -368*
package com.bitiknow.date;
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
/**
*
* @author pradeep
*
*/
public class LocalDateTimeTry {
public static void main(String[] args) {
// Date in String format.
String dateString = "2015-03-01";
// Converting date to Java8 Local date
LocalDate startDate = LocalDate.parse(dateString);
LocalDate endtDate = LocalDate.now();
// Range = End date - Start date
Long range = ChronoUnit.DAYS.between(startDate, endtDate);
System.out.println("Number of days between the start date : " + dateString + " and end date : " + endtDate
+ " is ==> " + range);
range = ChronoUnit.DAYS.between(endtDate, startDate);
System.out.println("Number of days between the start date : " + endtDate + " and end date : " + dateString
+ " is ==> " + range);
}
}
Everyone is saying to use ChronoUnit.DAYS.between but that just delegates to another method you could call yourself.每个人都说要使用 ChronoUnit.DAYS.between 但这只是委托给您可以调用自己的另一种方法。 So you could also do
firstDate.until(secondDate, ChronoUnit.DAYS)
.所以你也可以做
firstDate.until(secondDate, ChronoUnit.DAYS)
。
The docs for both actually mention both approaches and say to use whichever one is more readable.两者的文档实际上都提到了这两种方法,并说使用更易读的方法。
从当天获取圣诞节前的天数,试试这个
System.out.println(ChronoUnit.DAYS.between(LocalDate.now(),LocalDate.of(Year.now().getValue(), Month.DECEMBER, 25)));
Here you go:干得好:
public class DemoDate {
public static void main(String[] args) {
LocalDate today = LocalDate.now();
System.out.println("Current date: " + today);
//add 1 month to the current date
LocalDate date2 = today.plus(1, ChronoUnit.MONTHS);
System.out.println("Next month: " + date2);
// Put latest date 1st and old date 2nd in 'between' method to get -ve date difference
long daysNegative = ChronoUnit.DAYS.between(date2, today);
System.out.println("Days : "+daysNegative);
// Put old date 1st and new date 2nd in 'between' method to get +ve date difference
long datePositive = ChronoUnit.DAYS.between(today, date2);
System.out.println("Days : "+datePositive);
}
}
If the goal is just to get the difference in days and since the above answers mention about delegate methods would like to point out that once can also simply use -如果目标只是为了获得天数的差异,并且由于上述答案提到了委托方法,那么想指出一次也可以简单地使用 -
public long daysInBetween(java.time.LocalDate startDate, java.time.LocalDate endDate) {
// Check for null values here
return endDate.toEpochDay() - startDate.toEpochDay();
}
get days between two dates date is instance of java.util.Date
获取两个日期之间的天数 date 是 java.util.Date 的实例
public static long daysBetweenTwoDates(Date dateFrom, Date dateTo) {
return DAYS.between(Instant.ofEpochMilli(dateFrom.getTime()), Instant.ofEpochMilli(dateTo.getTime()));
}
I know this question is for Java 8, but with Java 9 you could use:我知道这个问题是针对 Java 8 的,但是对于 Java 9,您可以使用:
public static List<LocalDate> getDatesBetween(LocalDate startDate, LocalDate endDate) {
return startDate.datesUntil(endDate)
.collect(Collectors.toList());
}
Use the class or method that best meets your needs:使用最能满足您需求的类或方法:
A Duration measures an amount of time using time-based values (seconds, nanoseconds).持续时间使用基于时间的值(秒、纳秒)来测量时间量。
A Period uses date-based values (years, months, days). Period 使用基于日期的值(年、月、日)。
The ChronoUnit.between method is useful when you want to measure an amount of time in a single unit of time only, such as days or seconds.当您只想以单个时间单位(例如天或秒)测量时间量时, ChronoUnit.between 方法很有用。
https://docs.oracle.com/javase/tutorial/datetime/iso/period.html https://docs.oracle.com/javase/tutorial/datetime/iso/period.html
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;
LocalDate dateBefore = LocalDate.of(2020, 05, 20);
LocalDate dateAfter = LocalDate.now();
long daysBetween = ChronoUnit.DAYS.between(dateBefore, dateAfter);
long monthsBetween= ChronoUnit.MONTHS.between(dateBefore, dateAfter);
long yearsBetween= ChronoUnit.YEARS.between(dateBefore, dateAfter);
System.out.println(daysBetween);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.