java - 计算 Joda Time 的月差

标签 java date jodatime datediff

在第 4 行代码(忽略空格和注释)及之后我正在计算 2 个日期之间的月份差异。这可行,但看起来有点老套。有没有更好的办法?

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;
}

最佳答案

Months.monthsBetween(
     start.withDayOfMonth(1),
     end.withDayOfMonth(1)).getMonths()

关于java - 计算 Joda Time 的月差,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6844061/

相关文章:

java - 我怎样才能改进这段代码,这样就不会因为有多个同名对象而出现错误?

java - 使用 apache commons 配置的应用程序

java - 使用调用动态方法时出现 IllegalAccessException

php - 更改日期格式-PHP/SQL

java - 在 JodaTime 中创建特定时区的日期时间对象

java - 混合 log4j 1.x 和 log4j 2

php - php 日期的问题

r - 如何在 R 中迭代地更改观测值?

java - ISODateTimeFormat 格式化程序在高并发情况下性能好吗?

java - 将 joda 时区映射到 windows 时区(例如在 C# 中)