使用Java获取两个日期之间的差异 [英] Get difference between two dates in months using Java
问题描述
例如:
Startdate = 2013-04-03
enddate = 2013-05-03
结果应为1
如果间隔是
Startdate = 2013-04-03
enddate = 2014-04-03
结果应为12
使用以下代码,我可以在几天内得到结果。如何获取几个月?
Date startDate = new Date(2013,2,2);
日期endDate =新日期(2013,3,2);
int difInDays =(int)((endDate.getTime() - startDate.getTime())/(1000 * 60 * 60 * 24));
如果您无法使用JodaTime,您可以以下内容:
Calendar startCalendar = new GregorianCalendar();
startCalendar.setTime(startDate);
日历endCalendar = new GregorianCalendar();
endCalendar.setTime(endDate);
int diffYear = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR);
int diffMonth = diffYear * 12 + endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH);
请注意,如果您的日期是2013-01-31和2013-02-01,您会得到这样一个月的距离,这可能或可能不是你想要的。
I need to get difference between two dates using Java. I need my result to be in months.
Example:
Startdate = 2013-04-03 enddate = 2013-05-03 Result should be 1
if the interval is
Startdate = 2013-04-03 enddate = 2014-04-03 Result should be 12
Using the following code I can get the results in days. How can I get in months?
Date startDate = new Date(2013,2,2);
Date endDate = new Date(2013,3,2);
int difInDays = (int) ((endDate.getTime() - startDate.getTime())/(1000*60*60*24));
If you can't use JodaTime, you can do the following:
Calendar startCalendar = new GregorianCalendar();
startCalendar.setTime(startDate);
Calendar endCalendar = new GregorianCalendar();
endCalendar.setTime(endDate);
int diffYear = endCalendar.get(Calendar.YEAR) - startCalendar.get(Calendar.YEAR);
int diffMonth = diffYear * 12 + endCalendar.get(Calendar.MONTH) - startCalendar.get(Calendar.MONTH);
Note that if your dates are 2013-01-31 and 2013-02-01, you get a distance of 1 month this way, which may or may not be what you want.
这篇关于使用Java获取两个日期之间的差异的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!