Java8 calculate the difference between the number of days between two dates

In use Java8 range of new features in question should pay attention to the date when the acquisition method of the method Period.between.

@Test
public void test1(){
    LocalDate from = LocalDate.of(2018,10,1);
    System.out.println(Period.between(from,LocalDate.now()).getDays());
}

First, guess the number of days above code returns is how much? 15 days, you guessed yet?

If you do not understand why the 15 days, then we re-print of your other frame of mind, you might understand.

@Test
public void test1(){
    LocalDate from = LocalDate.of(2017,9,1);
    Period period = Period.between(from,LocalDate.now());

    System.out.println("2017-09-01到当前日期" + LocalDate.now());
    System.out.println("距离当前多少年:" + period.getYears());
    System.out.println("距离当前多少月:" + period.getMonths());
    System.out.println("距离当前多少日:" + period.getDays());
}

In the implementation of this program, the print log is as follows:

2017-09-01到当前日期2019-10-16
距离当前多少年:2
距离当前多少月:1
距离当前多少日:15

Read the following log information, to understand how it is now. If the time interval Period 2 years 1 month 15 days. Then () method is the third store 15 days by getDays. Instead of 2 years and 1 month 15 days total number of days.

So if the direct distance between the two dates would like to calculate how to do it? The following methods may be employed.

If you want the number of days of the calendar logic , use the following DAYS.between()method java.time.temporal.ChronoUnit:

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

If you want 24 hours of the date , ( duration ), you can use the Durationclass:

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

or:

@Test
public void test2() {
    LocalDate from = LocalDate.of(2017, 9, 1);
    long day = LocalDate.now().toEpochDay() - from.toEpochDay();
    System.out.println("距离当前多少日:" + day);
}

Implementation of the results:

距离当前多少日:775
Published 54 original articles · won praise 69 · Views 250,000 +

Guess you like

Origin blog.csdn.net/seanxwq/article/details/103765951