I want the number of months between 2 java.util.Date , not taking into account the number of days in a month. So I just want to compare the year and month.
Example:
monthsBetween(new Date(2012,01,28), new Date(2012,02,01)) ---> 1 monthsBetween(new Date(2012,02,27), new Date(2012,02,28)) ---> 0 monthsBetween(new Date(2012,03,28), new Date(2012,07,01)) ---> 4
I tried this (returns 0, expected 1) using Joda-time:
private static int monthsBetween(final Date fromDate, final Date toDate) { DateTime date1 = new DateTime().withDate(2012, 1, 20); DateTime date2 = new DateTime().withDate(2012, 2, 13); PeriodType monthDay = PeriodType.yearDayTime().withDaysRemoved(); Period difference = new Period(date1, date2, monthDay); int months = difference.getMonths(); return months; }
And also this (same results) using Joda-time:
private static int monthsBetween(final Date fromDate, final Date toDate) { return Months.monthsBetween(new DateTime(fromDate), new DateTime(toDate).getMonths(); }
How can i do this?