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

时间:2014-11-18 23:06:25

标签: java java-8 java-time days date-difference

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

功能需要抱怨这些限制:

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

14 个答案:

答案 0 :(得分:326)

如果您想要逻辑日历日,请使用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(以及其他文档:Oracle的Java 8)。

答案 1 :(得分:99)

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

ChronoUnit.DAYS.between(firstDate, secondDate)

答案 2 :(得分:32)

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

答案 3 :(得分:9)

您可以使用<select ng-model="search.bedrooms"> <option value="">Bedrooms</option> <option value="1">One</option> <option value="2">Two</option> <option value="3">Three</option> <option value="3">Four</option> </select> <select ng-model="search.bathrooms"> <option value="">Bathrooms</option> <option value="1">One</option> <option value="2">Two</option> </select> <select> <option value="180000">&pound;180,000</option> <option value="190000">&pound;190,000</option> <option value="200000">&pound;200,000</option> <option value="210000">&pound;210,000</option> <option value="220000">&pound;220,000</option> <option value="230000">&pound;230,000</option> <option value="240000">&pound;240,000</option> </select> <select> <option value="190000">&pound;190,000</option> <option value="200000">&pound;200,000</option> <option value="210000">&pound;210,000</option> <option value="220000">&pound;220,000</option> <option value="230000">&pound;230,000</option> <option value="240000">&pound;240,000</option> <option value="250000">&pound;250,000</option> </select> <div class="house-style-list"> <ul> <li ng-repeat="house in houses | filter:search:strict" ng-class=" {true: 'sold'}[house.sold == true]"> <a href="#/house-styles/the-astaire"> <img src="/images/house-styles/{{house.image}}"> <div class="content"> <h5>{{house.name}}</h5> <span class="bedrooms">{{house.bedrooms}}</span> <span class="bathrooms">{{house.bathrooms}}</span> <span class="price">&pound;{{house.price}}</span> </div> <span class="sold" ng-if="house.sold">SOLD</span> <span class="show-home" ng-if="house.showHome">Show Home</span> </a> </li> </ul> </div>

中的DAYS.between

e.g。

java.time.temporal.ChronoUnit

答案 4 :(得分:6)

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

输出 *开始日期:2015-03-01和结束日期之间的天数:2016-03-03是==&gt; 368。 **开始日期:2016-03-03和结束日期之间的天数:2015-03-01是==&gt; -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);

    }

}

答案 5 :(得分:6)

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

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

答案 6 :(得分: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);
    }
}

答案 7 :(得分:4)

  

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

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

ChronoUnit.DAYS 指的是完成24小时的天数。

答案 8 :(得分:3)

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

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

答案 9 :(得分:2)

  

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

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

答案 10 :(得分:1)

如果目标只是为了在几天之内获得差异,并且由于上述答案中提到了有关委托方法的内容,则希望指出,一次也可以简单地使用-

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

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

答案 11 :(得分:0)

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

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

答案 12 :(得分:0)

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

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

持续时间使用基于时间的值(秒,纳秒)测量时间量。

“期间”使用基于日期的值(年,月,日)。

ChronoUnit.between方法在只想以单个时间单位(例如天或秒)为单位的时间量时非常有用。

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

答案 13 :(得分:0)

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