Joda时间 – 两个日期之间的月份差异

我需要在两个日期之间获得差异,我正在使用Joda Time,问题是:

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会有问题。

将第一个日期更改为2015-02-02,Joda正确返回1个月:

 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-01-01 date2 指向的确切位置您可能已经提到了23:59:59 ,在这种情况下,从技术上讲,整整一个月还没有过去。

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

 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时间部分。

虽然其他答案是正确的,但他们仍然掩盖了真正的问题

它返回0,因为两个日期中间没有月份

不会。因为DateTime对象有时间部分,它返回0。 您创建了两个DateTime时间表,其中包含当前时刻(包括小时,分钟,秒和毫秒),然后修改日期部分。 如果你只想比较两个日期,没有理由这样做。 请改用LocalDate 。

 LocalDate date1 = new LocalDate(2015, 2, 1); LocalDate date2 = new LocalDate(2015, 1, 1); Months m = Months.monthsBetween(date1, date2); int monthDif = Math.abs(m.getMonths());//this return 1 

还需要注意的事实是,尽管Months文档没有说明它,但如果第一个日期在第二个日期之后,则Month可以包含负值。 所以我们需要使用Math.abs来真正计算两个日期之间的月数。

文档说:

创建一个月份,表示两个指定的部分日期时间之间的整月数。

但事实并非如此。 它确实计算了几个月的差异 。 不是几个月

计算方式取决于要使用的业务逻辑。 每个月的长度各不相同。 一个选项是,在monthsBetween()函数中,获取date1date2的月份开始,并进行比较。

就像是:

 DateTime firstOfMonthDate1 = new DateTime(date1.getYear(), date1.getMonthOfYear(), 1, 0, 0); DateTime firstOfMonthDate2 = new DateTime(date2.getYear(), date2.getMonthOfYear(), 1, 0, 0); Months m = Months.monthsBetween(firstOfMonthDate1, firstOfMonthDate2)