Search code examples
javadatejodatimeperioddate-difference

Why do I get a difference between two dates in Java?


Period period = new Period(startDate, endDate, PeriodType.yearMonthDay());

int years = period.getYears();
int months = period.getMonths();
int days = period.getDays();

if startDate = May 1, 1975 and endDate April 05, 2024
years = 48, months = 11, days = 4

but if startDate = April 30, 1975 and endDate April 05, 2024
years = 48, months = 11, days = 6

Why is the difference 2 days? expected days = 5! It just doesn’t look so logical when the user, choosing a birthday on the calendar, gets the age (from the current date) for May 1 - 4 days, and for April 30 - 6 days. This looks like an error.

joda time library is used


Solution

  • This seems perfectly correct to me.

    In the first example, where start date is 1/5/1975 - 48 years and 11 months after the start date is 1/4/2024. From that date, is 4 more days to come to 5/4/2024. So the difference between 1/5/1975 and 5/4/2024 is 48 years, 11 months and 4 days.

    In the second example, where start date is 30/4/1975 - 48 years and 11 months after the start date is 30/3/2024. From that date, it's 6 more days to come to 5/4/2024. So the difference between 30/4/1975 and 5/4/2024 is 48 years, 11 month and 6 days.

    The reason why a one-day difference in the start date creates a two-day difference in the result is that the "11 months" of the result aren't all the same length. In particular, in the first example, the 11 months includes March but not April; and in the second example, the 11 months includes April but not March. Since March and April have different numbers of days, the overall calculation turns out different.