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

Calculate days between two dates in Java 8

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

功能需要抱怨这些限制:

  • 防止日期保存时间错误
  • 输入是两个Date的对象(没有时间,我知道localdatetime,但我需要处理日期实例)

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

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

    如果你想要文字24小时日(持续时间),你可以使用Duration类代替:

    1
    2
    3
    4
    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)。


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

    1
    ChronoUnit.DAYS.between(firstDate, secondDate)


    您可以使用until()

    1
    2
    3
    4
    5
    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));


    您可以使用java.time.temporal.ChronoUnit中的DAYS.between

    例如

    1
    2
    3
    4
    5
    import java.time.temporal.ChronoUnit;

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

    If starDate and endDate are instance of java.util.Date, besides to
    @mohamed answer

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

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


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

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


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

    输出:
    *开始日期:2015-03-01和结束日期之间的天数:2016-03-03是==> 368。
    **开始日期:2016-03-03和结束日期之间的天数:2015-03-01是==> -368 *

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    19
    20
    21
    22
    23
    24
    25
    26
    27
    28
    29
    30
    31
    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);

        }

    }

    干得好:

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    14
    15
    16
    17
    18
    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);
        }
    }

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

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

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

    1
    2
    3
    4
    5
    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

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


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

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