2016-01-13 101 views
1

我需要在幾個月內兩個日期之間的差異之間的月份差,我使用約達時間,問題是這樣的:喬達時間 - 兩個日期

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會有問題。

+1

即使上面的問題是關於天,它是非常類似於你的問題,解決方案是相同的,調用'DateTime#toLocalDate()'將'LocalDate'傳遞給'Months#monthsBetween',而不是'DateTime '。 – Tom

+1

爲什麼你首先使用'new Datetime()。withDate()'?它創建當前時刻的DateTime實例,然後更改它(將時間字段保持原樣)。如果你想沒有時間創建新的特定日期,只需使用[LocalDate](http://www.joda.org/joda-time/apidocs/org/joda/time/LocalDate.html),然後選擇Months.monthsBetween (date1,date2)'會正常工作。 – djxak

回答

5

改變第一日至2015年2月2日,喬達正確返回1月份:

DateTime date1 = new DateTime().withDate(2015, 2, 2); 
DateTime date2 = new DateTime().withDate(2015, 1, 1); 

System.out.println(Months.monthsBetween(date2, date1).getMonths()); 
// Returns 1. 

所以我的猜測是,因爲你沒有提供時間部分,Joda無法準確確切地指出哪些時間點的2015-01-01date2指的是。 您也可以參考23:59:59,在這種情況下,技術上還沒有完整的月份。

如果你明確地提供零時間部分,它的工作原理爲您最初的預期:

DateTime date1 = new DateTime().withDate(2015, 2, 1).withTime(0, 0, 0, 0); 
DateTime date2 = new DateTime().withDate(2015, 1, 1).withTime(0, 0, 0, 0); 

System.out.println(Months.monthsBetween(date2, date1).getMonths()); 
// Returns 1. 

因此,我建議你在每個日期明確指定00:00:00時間部分。

+1

只是一個細節,DateTime有withTimeAtStartOfDay()方法 – TheJudge

-1

計算方式取決於要使用的業務邏輯。每個月的長度都不相同。一種選擇是在monthsBetween()函數中得到date1date2這個月的開始,然後比較一下。

喜歡的東西:

DateTime firstOfMonthDate1 = new DateTime(date1.getYear(), date1.getMonthOfYear(), 1, 0, 0); 
DateTime firstOfMonthDate2 = new DateTime(date2.getYear(), date2.getMonthOfYear(), 1, 0, 0); 
Months m = Months.monthsBetween(firstOfMonthDate1, firstOfMonthDate2) 
5

雖然其他答案是正確的,但它們仍然掩蓋了真正的問題。

則返回0,因爲沒有一個月在兩個日期

號則返回0,因爲有DateTime對象的時間部分的中間。您創建DateTime的兩個接口,填充當前時刻(包括小時,分鐘,秒和毫秒),然後修改即日期部分。如果你只想比較兩個日期,沒有理由去做。改爲使用LocalDate

LocalDate date1 = new LocalDate(2015, 2, 1); 
LocalDate date2 = new LocalDate(2015, 1, 1); 
Months m = Months.monthsBetween(date1, date2); 
int monthDif = Math.abs(m.getMonths());//this return 1 

還需要注意一個事實,即儘管Months文檔說一無所知,Month可以包含負值,如果第一次約會是第二次約會之後。所以我們需要使用Math.abs來真正計算兩個日期之間的月數。

docs說:

創建月表示的整月兩個指定部分日期時間之間的數量。

但事實並非如此。它真的會在幾個月內計算差異。不是的月數

+1

是的,我的錯。由於'date1'在'date2'之後,它實際上返回'-1'。 「Months.monthsBetween'文檔從未說過*月的時間段*可能是負面的。 :)但對於問題和接受的答案也是如此,並沒有改變任何東西。我編輯我的答案使用'Math.abs'。 – djxak

+0

我想最好向OP(在答案中)解釋爲什麼它返回-1與當前的代碼並使用'Months.monthsBetween(date2,date1);'而不是。它就像調用'X.compareTo(Y)'與'Y.compareTo(X)'一樣,結果也會被反轉:D。 – Tom