使用 Java 获取以月为单位的两个日期之间的差异
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/16558898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Get difference between two dates in months using Java
提问by ashu
I need to get difference between two dates using Java. I need my result to be in months.
我需要使用 Java 获取两个日期之间的差异。我需要我的结果在几个月内。
Example:
例子:
Startdate = 2013-04-03 enddate = 2013-05-03 Result should be 1
开始日期 = 2013-04-03 结束日期 = 2013-05-03 结果应该是 1
if the interval is
如果间隔是
Startdate = 2013-04-03 enddate = 2014-04-03 Result should be 12
开始日期 = 2013-04-03 结束日期 = 2014-04-03 结果应该是 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));
采纳答案by Etienne Miret
If you can't use JodaTime, you can do the following:
如果您不能使用 JodaTime,您可以执行以下操作:
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.
请注意,如果您的日期是 2013-01-31 和 2013-02-01,那么您将获得 1 个月的距离,这可能是您想要的,也可能不是。
回答by MadTech
You can use Joda time library for Java. It would be much easier to calculate time-diff between dates with it.
您可以使用 Java 的 Joda 时间库。用它计算日期之间的时间差异会容易得多。
Sample snippet for time-diff:
时间差异的示例片段:
Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();
回答by DaGLiMiOuX
You can try this:
你可以试试这个:
Calendar sDate = Calendar.getInstance();
Calendar eDate = Calendar.getInstance();
sDate.setTime(startDate.getTime());
eDate.setTime(endDate.getTime());
int difInMonths = sDate.get(Calendar.MONTH) - eDate.get(Calendar.MONTH);
I think this should work. I used something similar for my project and it worked for what I needed (year diff). You get a Calendar
from a Date
and just get the month's diff.
我认为这应该有效。我在我的项目中使用了类似的东西,它适用于我需要的东西(年份差异)。你Calendar
从 a得到 aDate
并得到当月的差异。