我知道有很多关于如何在Java中获取日期的问题,但我想要一个使用新的Java 8日期API的例子。我也知道JodaTime库,但我想要一个不依赖于外部库的方法。

该函数需要符合以下限制:

从日期保存时间防止错误 输入是两个日期对象(没有时间,我知道LocalDateTime,但我需要用日期实例这样做)


当前回答

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

    }

}

其他回答

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

如果startDate和endDate是java.util.Date的实例

我们可以从ChronoUnit enum中使用between()方法:

public long between(Temporal temporal1Inclusive, Temporal temporal2Exclusive) {
    //..
}

ChronoUnit。DAYS表示完成24小时的天数。

import java.time.temporal.ChronoUnit;

ChronoUnit.DAYS.between(startDate.toInstant(), endDate.toInstant());

//OR 

ChronoUnit.DAYS.between(Instant.ofEpochMilli(startDate.getTime()), Instant.ofEpochMilli(endDate.getTime()));

DAYS.between

你可以使用DAYS。from java.time.temporal.ChronoUnit

e.g.

import java.time.temporal.ChronoUnit;
...

long totalDaysBetween(LocalDate dateBefore, LocalDate dateAfter) {
    return DAYS.between(dateBefore, dateAfter);

根据VGR的评论,以下是你可以使用的方法:

ChronoUnit.DAYS.between(firstDate, secondDate)

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

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