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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27005861/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 03:39:12  来源:igfitidea点击:

Calculate days between two dates in Java 8

javajava-8java-timedaysdate-difference

提问by Marcos

I know there are lots of questions on SO about how to get, but I want and example using new Java 8 Date api. I also know JodaTime library, but I want a work way without external libraries.

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

Function needs to complain with these restrictions:

函数需要抱怨这些限制:

  1. Prevent errors from date savetime
  2. Input are two Date's objects (without time, I know localdatetime, but I need to do with date instances)
  1. 防止日期保存时间出错
  2. 输入是两个Date的对象(没有时间,我知道localdatetime,但我需要处理日期实例)

采纳答案by syntagma

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 Durationclass 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.

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

回答by Sunil B

Based on VGR's comments here is what you can use:

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

ChronoUnit.DAYS.between(firstDate, secondDate)

回答by Piotr Fryga

You can use DAYS.betweenfrom java.time.temporal.ChronoUnit

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

e.g.

例如

import java.time.temporal.ChronoUnit;

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

回答by nazar_art

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

回答by Pradeep Padmarajaiah

Use the DAYS in enum java.time.temporal.ChronoUnit. Below is the Sample Code :

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

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

    }

}

回答by Ash_P

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

回答by survivor_27

Get number of days before Christmas from current day , try this

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

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

回答by nafg

Everyone is saying to use ChronoUnit.DAYS.between but that just delegates to another method you could call yourself. So you could also do firstDate.until(secondDate, ChronoUnit.DAYS).

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

The docs for both actually mention both approaches and say to use whichever one is more readable.

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

回答by Mohamed.Abdo

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

回答by levenshtein

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