Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get a Period of Days between two Dates

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());
}
like image 434
kerner1000 Avatar asked May 01 '17 21:05

kerner1000


People also ask

How do you count the days between two periods?

The average menstrual cycle is 28 days, which means the average time between periods for most girls is 28 days. So, if you want a very general estimate of when your next period is coming, count 28 days from the first day of your last period.

How do I get days between two dates in SQL?

The DATEDIFF() function returns the difference between two dates.

How do I calculate days delay in Excel?

To find the number of days between these two dates, you can enter “=B2-B1” (without the quotes into cell B3). Once you hit enter, Excel will automatically calculate the number of days between the two dates entered.


2 Answers

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.

like image 81
bhspencer Avatar answered Sep 27 '22 17:09

bhspencer


JavaDoc for java.time.Period#getDays() says:

returns the amount of days of this period, may be negative

I guess this is missleading and it does not really return the total amount of days.

I use now

final long daysElapsed = ChronoUnit.DAYS.between(LocalDate.of(2017, 06, 01), LocalDate.of(2017, 07, 01));

which works as expected.

like image 34
kerner1000 Avatar answered Sep 27 '22 17:09

kerner1000