Calculate month difference in Joda Time

前端 未结 3 936
野趣味
野趣味 2020-12-11 02:49

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 be

相关标签:
3条回答
  • 2020-12-11 03:38

    This is the solution I came up with when commenting on Bozho

    int handleAllowance(LocalDate today) {
    
        int allowance = membership.allowance();
        if (allowance == 0) return 0;
    
        // calculate month difference
        int allowanceMonths = Months.monthsBetween(lastAllowanceUpdate.withDayOfMonth(1), today.withDayOfMonth(1)).getMonths();
    
        // if update was last month or earlier
        if (allowanceMonths > 0) {
    
            // ...and if today is on or past update day
            int updateDay = Math.min(allowanceDay, today.dayOfMonth().getMaximumValue());
            if (today.getDayOfMonth() >= updateDay) {
    
                // give credits (multiply with months in the rare case this process consecutively fails to run for 2 months or more)
                final int totalAllowance = allowance * allowanceMonths;
                giveCredits(totalAllowance);
    
                // update day
                lastAllowanceUpdate = lastAllowanceUpdate.plusMonths(allowanceMonths);
    
                // return the allowance given
                return totalAllowance;
    
            }
    
        }
    
        return 0;
    }
    
    0 讨论(0)
  • 2020-12-11 03:47
    Months.monthsBetween(
         start.withDayOfMonth(1),
         end.withDayOfMonth(1)).getMonths()
    
    0 讨论(0)
  • 2020-12-11 03:55

    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();
      }
    
    0 讨论(0)
提交回复
热议问题