Get a Period of Days between two Dates

kerner1000 :

I use java.time.Period#getDays() to get the number of days for a given period of LocalDates.

It seems to work for most cases, but for a whole month, I get a period of zero days.

The following test case fails (java.lang.AssertionError: expected:<30> but was:<0>):

@Test
public void testOneMonthPeriodDays() {
    Period p = Period.between(LocalDate.of(2017, 06, 01), LocalDate.of(2017, 07, 01));
    assertEquals(30, p.getDays());
}
bhspencer :

I believe this is the correct result. If you run the following test you will see that getMonths() returns 1. It seems that getDays is not get the total days but get the remainder days.

@Test
public void testOneMonthPeriodDays() {
    Period p = Period.between(LocalDate.of(2017, 06, 01), LocalDate.of(2017, 07, 01));
    assertEquals(0, p.getDays());
    assertEquals(1, p.getMonths());
}

To get the total number of days between two dates see this question Calculate days between two dates in Java 8

To quote the answer given in that question:

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

Note that DAYS is member of java.time.temporal.ChronoUnit enum.

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=475597&siteId=1