【发布时间】:2011-10-14 05:11:59
【问题描述】:
在第 4 行代码(忽略空格和 cmets)及之后,我正在计算 2 个日期之间的月差。这可行,但看起来有点hacky。有没有更好的办法?
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;
}
【问题讨论】:
-
一个问题,虽然题外话:
allowance是常量吗?如果没有,final int totalAllowance = allowance * allowanceMonths;可能会为allowanceMonths > 1产生不同的结果,而不是运行整个部分allowanceMonths次。 -
定义常量。它的值取决于用户的订阅类型,在这 2 个月的时间里可能会发生变化。但它不会以任何其他方式改变。因此,我想如果该过程未能运行 2 个月并且用户决定在它再次运行的前一天升级订阅,他会获得比预期更多的津贴。不过没关系,这不是致命错误,
allowanceMonths不太可能真的大于 1 -
对于常量,我的意思是“两次运行之间的值是否会发生变化,结果是否取决于学分或类似情况”?由于您似乎有固定的津贴(除非用户更改订阅类型),这可能没问题。您也可以每个月都这样做,并让每个月的订阅类型更准确。
-
@Thomas:我可以,但目前无法找到用户过去的订阅,也不值得为此付出努力。
标签: java date jodatime datediff