我想计算2个日期的月份和日期之间的差异,我不想考虑一个月是30天,并以毫秒为单位获取时间并转换它们,我不想要使用像Joda这样的库,我也找到了一个使用LocalDate的解决方案,但我使用的是Java 7。 我寻找我的问题的答案,但找不到任何,我尝试了很多方法,我尝试创建一个日历,并以毫秒为单位传递我的2个日期之间的差异,但如果我试图获得15/04之间的差异和15/5我会得到30天而不是1个月,下面是代码
Calendar c = Calendar.getInstance();
c.set(Calendar.YEAR, 2013);
c.set(Calendar.MONTH, Calendar.APRIL);
c.set(Calendar.DAY_OF_MONTH, 15);
Date startDate = c.getTime();
c.set(Calendar.YEAR, 2013);
c.set(Calendar.MONTH, Calendar.MAY);
c.set(Calendar.DAY_OF_MONTH, 15);
Date lastDate = c.getTime();
Calendar diffCal = Calendar.getInstance();
diffCal.setTimeInMillis(lastDate.getTime() - startDate.getTime());
int months = ((diffCal.get(Calendar.YEAR) - 1970) * 12) + diffCal.get(Calendar.MONTH);
int days = diffCal.get(Calendar.DAY_OF_MONTH) - 1;
System.out.println("month(s) = " + months); // month(s) = 0
System.out.println("day(s) = " + days); // day(s) = 30
我可以使用什么来获得两个月之前的几个月之间的差异?
编辑:我写了下面的代码,似乎给了我想要的东西,可以用它吗
Date startDate = sdf.parse("31/05/2016");
Date endDate = sdf.parse("1/06/2016");
Calendar startCalendar = Calendar.getInstance();
Calendar endCalendar = Calendar.getInstance();
startCalendar.setTime(startDate);
endCalendar.setTime(endDate);
int months = 0, days = 0;
months += ((endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR)) * 12);
int startDays = startCalendar.get(Calendar.DAY_OF_MONTH);
int endDays = endCalendar.get(Calendar.DAY_OF_MONTH);
if(endDays >= startDays) {
months += (endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH));
days += (endDays - startDays);
} else {
months += (endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH) - 1);
days += ((startCalendar.getActualMaximum(Calendar.DAY_OF_MONTH) - startDays) + endDays);
}
System.out.println("Difference");
System.out.println("Month(s): " + months);
System.out.println("Day(s): " + days);
答案 0 :(得分:1)
您在研究中回答了自己的问题。 JDK7不支持您想要的。您有三种选择: