Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calculate month difference in Joda Time

At the 4th line of code (ignore whitespace & comments) and beyond I'm calculating the month difference between 2 dates. This works, but looks a bit hacky. Is there a better way?

int handleAllowance(LocalDate today) {

    int allowance = membership.allowance();
    if (allowance == 0) return 0;

    // if update was last month (or earlier)
    int months = today.monthOfYear().getMaximumValue() - today.monthOfYear().getMinimumValue(); // yeah, 12, but just to be 100% correct :-)
    int curMonth = (today.getYear()               * months) + today.              getMonthOfYear();
    int updMonth = (lastAllowanceUpdate.getYear() * months) + lastAllowanceUpdate.getMonthOfYear();
    if (curMonth > updMonth) {

        // ...and if today is on or past update day
        int updateDay = Math.min(allowanceDay, today.dayOfMonth().getMaximumValue());
        if (today.getDayOfMonth() >= updateDay) {

            // number of months to give allowance (in the rare case this process fails to run for 2 months or more)
            int allowanceMonths = curMonth - updMonth;

            // give credits
            final int totalAllowance = allowance * allowanceMonths;
            giveCredits(totalAllowance);

            // update day
            lastAllowanceUpdate = lastAllowanceUpdate.plusMonths(allowanceMonths);

            // return the allowance given
            return totalAllowance;

        }

    }

    return 0;
}
like image 971
Bart van Heukelom Avatar asked Jul 27 '11 12:07

Bart van Heukelom


Video Answer


2 Answers

Months.monthsBetween(
     start.withDayOfMonth(1),
     end.withDayOfMonth(1)).getMonths()
like image 104
Bozho Avatar answered Oct 28 '22 21:10

Bozho


This is pretty similar to Bozho's solution:

  public static YearMonth toYearMonth(LocalDate localDate) {
    return new YearMonth(localDate.getYear(), localDate.getMonthOfYear());
  }

  public static int monthSwitches(LocalDate date1,LocalDate date2) {
    return Months.monthsBetween(toYearMonth(date1),toYearMonth(date2)).getMonths();
  }
like image 41
Sebastien Lorber Avatar answered Oct 28 '22 21:10

Sebastien Lorber