java – Joda时间 – 两个日期之间的月份差异
发布时间:2020-12-15 05:21:49 所属栏目:Java 来源:网络整理
导读:参见英文答案 Number of days between two dates in Joda-Time????????????????????????????????????8个 我需要在两个日期之间获得差异,我正在使用Joda Time,问题是: DateTime date1 = new DateTime().withDate(2015,2,1);DateTime date2 = new DateTime().
参见英文答案 >
Number of days between two dates in Joda-Time????????????????????????????????????8个
我需要在两个日期之间获得差异,我正在使用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); DateTime date2 = new DateTime().withDate(2015,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,1).withTime(0,0); DateTime date2 = new DateTime().withDate(2015,0); System.out.println(Months.monthsBetween(date2,date1).getMonths()); // Returns 1. 因此,我建议您明确指定每个日期的00:00:00时间部分. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |