在Java 8中计算两个日期之间的天数

我知道在SO上有很多关于如何在Java中获得Date的问题,但我想要一个使用新的Java 8 Date API的例子。我也知道JodaTime库,但我想要一个不依赖于外部库的方法。

该函数需要符合以下限制:

  1. 从日期保存时间防止错误
  2. 输入是两个Date对象(没有时间,我知道LocalDateTime,但我需要用Date实例这样做)
362269 次浏览

如果你想要逻辑日历日,使用java.time.temporal.ChronoUnit中的DAYS.between()方法:

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

如果你想要每天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

有关更多信息,请参阅这个文档

根据VGR的评论,以下是你可以使用的方法:

ChronoUnit.DAYS.between(firstDate, secondDate)

DAYS.between

你可以从java.time.temporal.ChronoUnit中使用DAYS.between

如。

import java.time.temporal.ChronoUnit;
...


long totalDaysBetween(LocalDate dateBefore, LocalDate dateAfter) {
return DAYS.between(dateBefore, dateAfter);

你可以使用直到:

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

输出:

Until christmas: P5M21D
Until christmas (with crono): 174

正如注释中提到的,如果没有指定任何单位,until将返回

文档片段:

ISO-8601日历系统中基于日期的时间量,例如“2年3个月4天”。
该类以年、月和日为单位对时间的数量或数量进行建模。

.

.

.

使用枚举java.time.temporal.ChronoUnit中的DAYS。下面是示例代码:

< >强输出: *开始日期: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);


}


}

给你:

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

从现在开始计算圣诞节前的天数,试试这个

System.out.println(ChronoUnit.DAYS.between(LocalDate.now(),LocalDate.of(Year.now().getValue(), Month.DECEMBER, 25)));

每个人都说使用chronounit。days。between但那只是委托给另一个你可以自己调用的方法。所以你也可以做firstDate.until(secondDate, ChronoUnit.DAYS)

这两种方法的文档实际上都提到了这两种方法,并说使用哪一种更易于阅读。

date是java.util.Date的实例

public static long daysBetweenTwoDates(Date dateFrom, Date dateTo) {
return DAYS.between(Instant.ofEpochMilli(dateFrom.getTime()), Instant.ofEpochMilli(dateTo.getTime()));
}

如果目标只是得到天的差异,而且既然上面的答案提到了关于委托方法,想指出的是,一旦也可以简单地使用-

public long daysInBetween(java.time.LocalDate startDate, java.time.LocalDate endDate) {
// Check for null values here


return endDate.toEpochDay() - startDate.toEpochDay();
}

如果startDate可以endDatejava.util.Date的实例

我们可以从< em > ChronoUnit < / em > enum中使用()之间的< em > < / em >方法:

public long between(Temporal temporal1Inclusive, Temporal temporal2Exclusive) {
//..
}

ChronoUnit。天计算完成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()));

我知道这个问题是针对Java 8的,但是对于Java 9,你可以使用:

public static List<LocalDate> getDatesBetween(LocalDate startDate, LocalDate endDate) {
return startDate.datesUntil(endDate)
.collect(Collectors.toList());
}

使用最能满足您需求的类或方法:

  • 持续时间类,
  • 类,
  • ChronoUnit.between方法。

Duration使用基于时间的值(秒、纳秒)度量时间量。

Period使用基于日期的值(年、月、日)。

ChronoUnit。当您希望仅以单个时间单位(如天或秒)测量时间量时,Between方法非常有用。

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