计算Joda时间的月差 [英] Calculate month difference in Joda Time
本文介绍了计算Joda时间的月差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在第4行代码(忽略空白和评论)以外,我计算2个日期之间的月份差异。这个工作,但看起来有点黑客。有没有更好的方法?
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;
}
推荐答案
Months.monthsBetween(
start.withDayOfMonth(1),
end.withDayOfMonth(1)).getMonths()
这篇关于计算Joda时间的月差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文