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

问题描述 投票:196回答:12

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

功能需要抱怨这些限制:

  1. 防止日期保存时间错误
  2. 输入是两个Date的对象(没有时间,我知道localdatetime,但我需要处理日期实例)
java java-8 java-time days date-difference
12个回答
358
投票

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

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

有关更多信息,请参阅this document


2
投票

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

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

2
投票

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

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

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

0
投票

我知道这个问题适用于Java 8,但使用Java 9可以使用:

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

107
投票

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

ChronoUnit.DAYS.between(firstDate, secondDate)

35
投票

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

10
投票

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

EG

import java.time.temporal.ChronoUnit;

public long getDaysCountBetweenDates(LocalDate dateBefore, LocalDate dateAfter) {
    return DAYS.between(dateBefore, dateAfter);
}

7
投票

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

    }

}

6
投票

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

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


6
投票

如果starDate和endDate是java.util.Date的实例,除了@mohamed回答

Integer noOfDays = ChronoUnit.DAYS.between(startDate.toInstant(), endDate.toInstant());

但ChronoUnit.DAYS计算完成24小时的天数。


4
投票

干得好:

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

3
投票

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

System.out.println(ChronoUnit.DAYS.between(LocalDate.now(),LocalDate.of(Year.now().getValue(), Month.DECEMBER, 25)));
© www.soinside.com 2019 - 2024. All rights reserved.