如何使用 Java 的 Joda API 仅计算月份差异
我正在编写一个程序,该程序应该只计算两个给定日期之间的月份并将值返回给程序。例如,如果我必须计算 4 月 1 日到 6 月 30 日之间的月数(即一个季度,3 个月),我使用以下代码:
DateTime start = new DateTime().withDate(2011, 4, 1);
DateTime end = new DateTime().withDate(2011, 6, 30);
Months mt = Months.monthsBetween(start, end);
int monthDiff = mt.getMonths();
使用此代码,我仍然得到“2”作为月数,而实际上是“3”个月。这是我想要的一个例子。我只计算月数(即从开始月的第一天到结束月的最后一天),不需要额外的分析,如天、周、小时等。我如何实现这一点?
任何帮助将不胜感激。
I am writing a program that is supposed to just calculate the months between 2 given dates and return the value to the program. For instance, if I have to calculate the number of months between 1 April and 30 June (which is a quarter, 3 months), and I use the following code:
DateTime start = new DateTime().withDate(2011, 4, 1);
DateTime end = new DateTime().withDate(2011, 6, 30);
Months mt = Months.monthsBetween(start, end);
int monthDiff = mt.getMonths();
Using this, I am still getting "2" as the number of months, whereas it is actually "3" months. This is an example of what I want. I am only calculating the number of months (i.e. from 1st of the start month t the last date of the end month) and I dont need additional analysis like days, weeks, hours, etc. How do I achieve this?
Any help would be appreciated.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
发布评论
评论(6)
Joda 算法正确计算了这两个日期之间的差异。这个伪代码将是解释其工作原理的最简单方法:
// (1)
monthsBetween(2011.6.14, 2011.4.15) = 1
monthsBetween(2011.6.15, 2011.4.15) = 2
// (2)
monthsBetween(2011.6.30, 2011.4.1) = 2
monthsBetween(2011.7.1, 2011.4.1) = 3
要做你想做的事,你需要“改进”joda算法:
- 计算两个日期之间的距离(使用正常的monthsBetween)
- 如果你有特定情况:一个月的最后一天在一个日期和第二个日期的该月第一天,将最终结果加 +1。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
您需要
withDaysRemoved()
部分来确保月数加一有效。否则,2011-04-15
和2011-06-14
等两个日期仍会导致答案为2
You need the
withDaysRemoved()
part to ensure that adding one to the number of months works. Otherwise two dates such as2011-04-15
and2011-06-14
would still result in the answer being2