乔达时间-两个日期之间的月份差 [英] Joda Time - difference in months between two dates

查看:77
本文介绍了乔达时间-两个日期之间的月份差的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要得到两个日期之间的月份差,我使用的是乔达时间,问题是这样的:

I need to get the difference in months between two dates, I'm using Joda Time, the problem is this:

DateTime date1 = new DateTime().withDate(2015, 2, 1);
DateTime date2 = new DateTime().withDate(2015, 1, 1);
Months m = Months.monthsBetween(date1, date2);
int monthDif = m.getMonths();//this return 0 

它返回0,因为两个日期中间没有月份,我需要返回两个月之间相隔几个月而不是几个月的差值,并且当日期相同时,加1将是有问题的.

it returns 0 because there is no month in the middle of the two dates, I need to return the difference in months not a few months in between, and add 1 would be problematic when the dates are the same.

推荐答案

将第一个日期更改为2015年2月2日,乔达正确地返回了1个月:

Changing the first date to 2015-02-02, Joda correctly returns 1 month:

DateTime date1 = new DateTime().withDate(2015, 2, 2);
DateTime date2 = new DateTime().withDate(2015, 1, 1);

System.out.println(Months.monthsBetween(date2, date1).getMonths());
// Returns 1.

所以我的猜测是,由于您没有提供时间部分,Joda无法准确地准确地指出 2015年1月1日的哪个时间点 date2. 您可能已经提到23:59:59 ,在这种情况下,从技术上讲,整整一个月还没有过去.

So my guess is that because you didn't provide a time portion, Joda cannot be precise about exactly which point in time of 2015-01-01 date2 refers to. You might have as well referred to 23:59:59, in which case a full month wouldn't have elapsed yet, technically.

如果您明确提供零时间部分,它将按您最初的预期工作:

If you provide a zero time portion explicitly, it works as you initially expected:

DateTime date1 = new DateTime().withDate(2015, 2, 1).withTime(0, 0, 0, 0);
DateTime date2 = new DateTime().withDate(2015, 1, 1).withTime(0, 0, 0, 0);

System.out.println(Months.monthsBetween(date2, date1).getMonths());
// Returns 1.

因此,我建议您明确在每个日期中指定一个00:00:00的时间部分.

Therefore, I recommend you specify a 00:00:00 time portion in each date explicitly.

这篇关于乔达时间-两个日期之间的月份差的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆