2013-05-15 46 views
27

我需要使用Java在兩個日期之間獲得差異。我需要我的結果在幾個月內。使用Java在幾個月內獲取兩個日期之間的差異

實施例:

開始日期2013年4月3日= ENDDATE = 2013年5月3日 結果應該是1

如果間隔是

開始日期= 2013-04-03 enddate = 2014-04-03 結果應該是12

使用下面的代碼我可以在幾天內得到結果。我怎麼能在幾個月內?

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)); 
+0

你可以使用外部庫,比如JodaTime嗎? – Keppil

+3

如果使用JodaTime那麼,這是一個簡單的答案類似的問題在這裏:http://stackoverflow.com/questions/6844061/calculate-month-difference-in-joda-time – maba

+1

你想2013-01-之間是什麼31和2013-02-01? 0個月還是1個月? –

回答

88

如果您不能使用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); 

請注意,如果您的日期是2013年1月31日和2013年2月1日,你會得到1個月的距離這樣,這可能會或可能不是你想要的。

+0

+1這將適用於每年的差異。 (即)'Startdate = 2014-04-03 enddate = 2013-04-03正如OP所說,結果應該是12'。 **更新**是的,即使只有1天的差異,他也會得到1個月的差異,但是OP指定他需要幾個月。 1個月它們在這些日期之間並不是真正的差異,但0它並不是真正的差異。爲此,如果你想要0個月,你可以做一些像'Math.floor'或類似的東西。 – DaGLiMiOuX

+0

@ Etienne Miret:我收到以下錯誤。方法startCalendar(int)對於類型 – ashu

+1

未定義@ashu'startCalendar(int)'不是方法。也許,你的語法錯誤。你必須做'startCalendar.setTime(int)'。在這種情況下,'int'是'startDate.getTime()'。所以你需要在你的代碼中使用'startCalendar.setTime(startDate。getTime())' – DaGLiMiOuX

4

您可以使用Java的Joda時間庫。計算日期之間的時差會容易得多。

時間-DIFF示例代碼段:

Days d = Days.daysBetween(startDate, endDate); 
int days = d.getDays(); 
+0

僅供參考,Joda-Time項目現在處於維護模式,其團隊建議遷移到java.time類。 –

-4

你可以試試這個:

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); 

我認爲這應該工作。我爲我的項目使用了類似的東西,它爲我所需要的(年差)工作。你從Date得到Calendar,只是得到月份的差異。

+10

如果這兩個日期屬於不同年份,則不起作用。 –

+0

@EtienneMiret確實如此。這將只適用於同一年的日期。 – DaGLiMiOuX