计算乔达时间的月差
在代码的第四行(忽略空格和注释)及之后,我正在计算两个日期之间的月份差异。这可行,但看起来有点老套。有更好的办法吗?
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;
}
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;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这与 Bozho 的解决方案非常相似:
This is pretty similar to Bozho's solution:
这是我在评论 Bozho 时想到的解决方案
This is the solution I came up with when commenting on Bozho