Get the period of days between two dates
I am using java.time.Period#getDays()
to get the number of days for a given period LocalDate
s.
This seems to work most of the time, but for a full month, I get a period of zero.
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());
}
source to share
I believe this is the correct result. If you do the following test, you will see that getMonths () returns 1. It seems that getDays is not getting the total days, but the remaining 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 this question:
LocalDate dateBefore;
LocalDate dateAfter;
long daysBetween = DAYS.between(dateBefore, dateAfter);
source to share
JavaDoc for java.time.Period#getDays()
says:
returns the number of days of this period, can be negative
I assume these are gaps and it doesn't actually return the total number of days.
Now I am using
final long daysElapsed = ChronoUnit.DAYS.between(LocalDate.of(2017, 06, 01), LocalDate.of(2017, 07, 01));
which works as expected.
source to share