Java Date month difference

As the rest say, if there’s a library that will give you time differences in months, and you can use it, then you might as well.

Otherwise, if y1 and m1 are the year and month of the first date, and y2 and m2 are the year and month of the second, then the value you want is:

(y2 - y1) * 12 + (m2 - m1) + 1;

Note that the middle term, (m2 – m1), might be negative even though the second date is after the first one, but that’s fine.

It doesn’t matter whether months are taken with January=0 or January=1, and it doesn’t matter whether years are AD, years since 1900, or whatever, as long as both dates are using the same basis. So for example don’t mix AD and BC dates, since there wasn’t a year 0 and hence BC is offset by 1 from AD.

You’d get y1 etc. either from the dates directly if they’re supplied to you in a suitable form, or using a Calendar.

Leave a Comment