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

时间:2022-05-18 01:56:17

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日期api。我也知道JodaTime库,但是我想要一种没有外部库的工作方式。

Function needs to complain with these restrictions:

函数需要抱怨这些限制:

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

8 个解决方案

#1


214  

If you want logical calendar days, use DAYS.between() method from java.time.temporal.ChronoUnit:

如果您需要逻辑日历天,请使用day. between()方法和java.time. chronounit:

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

If you want literal 24 hour days, (a duration), you can use the Duration class 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 (and other documents re:Java 8 from Oracle).

有关更多信息,请参阅此文档(以及Oracle的其他文档re:Java 8)。

#2


73  

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

基于VGR的评论,以下是您可以使用的:

ChronoUnit.DAYS.between(firstDate, secondDate)

#3


18  

You can use 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));

#4


7  

You can use DAYS.between from java.time.temporal.ChronoUnit

您可以使用天。从java.time.temporal.ChronoUnit之间

e.g.

如。

import java.time.temporal.ChronoUnit;

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

#5


3  

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

#6


2  

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

使用enum java.time.颞颥中的天数。ChronoUnit。下面是示例代码:

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

    }

}

#7


2  

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

每个人都说要用时间。但这只是代表了另一种方法,你可以这样称呼自己。你也可以做firstDate。直到(secondDate ChronoUnit.DAYS)。

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

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

#8


0  

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

#1


214  

If you want logical calendar days, use DAYS.between() method from java.time.temporal.ChronoUnit:

如果您需要逻辑日历天,请使用day. between()方法和java.time. chronounit:

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

If you want literal 24 hour days, (a duration), you can use the Duration class 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 (and other documents re:Java 8 from Oracle).

有关更多信息,请参阅此文档(以及Oracle的其他文档re:Java 8)。

#2


73  

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

基于VGR的评论,以下是您可以使用的:

ChronoUnit.DAYS.between(firstDate, secondDate)

#3


18  

You can use 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));

#4


7  

You can use DAYS.between from java.time.temporal.ChronoUnit

您可以使用天。从java.time.temporal.ChronoUnit之间

e.g.

如。

import java.time.temporal.ChronoUnit;

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

#5


3  

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

#6


2  

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

使用enum java.time.颞颥中的天数。ChronoUnit。下面是示例代码:

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

    }

}

#7


2  

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

每个人都说要用时间。但这只是代表了另一种方法,你可以这样称呼自己。你也可以做firstDate。直到(secondDate ChronoUnit.DAYS)。

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

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

#8


0  

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