333

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

该功能需要符合以下限制:

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

14 回答 14

537

如果您想要逻辑日历日,请使用以下DAYS.between()方法java.time.temporal.ChronoUnit

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

如果您想要文字 24 小时 days持续时间),则可以改用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

有关详细信息,请参阅此文档

于 2014-11-18T23:24:12.590 回答
161

根据 VGR 的评论,您可以使用以下内容:

ChronoUnit.DAYS.between(firstDate, secondDate)
于 2014-11-18T23:29:56.540 回答
50

您可以使用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));

输出:

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

如评论中所述 - 首先untill()返回Period

来自文档的片段:

ISO-8601 日历系统中基于日期的时间量,例如“2 年 3 个月 4 天”。
此类以年、月和日为单位对时间量或时间量进行建模。有关此类的基于时间的等效项,请参见 Duration。

于 2015-08-30T16:57:13.153 回答
18

DAYS.between

你可以使用DAYS.betweenjava.time.temporal.ChronoUnit

例如

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

long totalDaysBetween(LocalDate dateBefore, LocalDate dateAfter) {
    return DAYS.between(dateBefore, dateAfter);
于 2015-05-19T08:20:24.223 回答
17

如果startDateendDatejava.util.Date的实例

我们可以使用ChronoUnit 枚举中的between()方法:

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

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()));
于 2019-02-20T16:13:45.643 回答
10

使用枚举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);

    }

}
于 2016-03-03T05:34:06.857 回答
10

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

两者的文档实际上都提到了这两种方法,并说要使用更具可读性的方法。

于 2018-01-05T20:21:33.383 回答
7

从当天获取圣诞节前的天数,试试这个

System.out.println(ChronoUnit.DAYS.between(LocalDate.now(),LocalDate.of(Year.now().getValue(), Month.DECEMBER, 25)));
于 2017-10-05T22:51:50.473 回答
6

干得好:

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);
    }
}
于 2016-08-15T17:13:13.877 回答
4

如果目标只是在几天内获得差异,并且由于上述答案提到了委托方法想指出一次也可以简单地使用 -

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

  return endDate.toEpochDay() - startDate.toEpochDay();
}
于 2018-11-30T06:37:49.537 回答
3

获取两个日期之间的天数 date 是 java.util.Date 的实例

public static long daysBetweenTwoDates(Date dateFrom, Date dateTo) {
            return DAYS.between(Instant.ofEpochMilli(dateFrom.getTime()), Instant.ofEpochMilli(dateTo.getTime()));
        }
于 2018-10-02T14:16:16.777 回答
3

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

public static List<LocalDate> getDatesBetween(LocalDate startDate, LocalDate endDate) {
    return startDate.datesUntil(endDate)
      .collect(Collectors.toList());
}
于 2019-06-03T09:24:22.593 回答
3

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

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

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

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

当您只想测量单个时间单位(例如天或秒)中的时间量时,ChronoUnit.between 方法很有用。

https://docs.oracle.com/javase/tutorial/datetime/iso/period.html

于 2019-10-01T12:09:44.393 回答
1
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);
于 2020-08-01T05:40:59.983 回答