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

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

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


当前回答

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

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

如果你想要24小时的天,(一个duration),你可以使用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

更多信息请参考本文档。

其他回答

给你:

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

从现在开始计算圣诞节前的天数,试试这个

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

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

Duration类, 周期类, 或者ChronoUnit。之间的方法。

Duration使用基于时间的值(秒、纳秒)度量时间量。

Period使用基于日期的值(年、月、日)。

ChronoUnit。当您希望仅以单个时间单位(如天或秒)测量时间量时,Between方法非常有用。

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

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

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

如果你想要24小时的天,(一个duration),你可以使用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

更多信息请参考本文档。

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

ChronoUnit.DAYS.between(firstDate, secondDate)