2017-04-11 21 views
0

我想使用喬達時間來獲得兩個日期之間的差異,但不知何故,我無法獲得確切的區別。使用喬達時間無法獲得兩個日期之間的正確區別

 LocalDate endofCentury = new LocalDate(2014, 01, 01); 

     LocalDate now = LocalDate.now(); //2017-04-11 

     Period diff = new Period(endofCentury, now); 

     System.out.printf("Difference is %d years, %d months and %d days old", 
          diff.getYears(), diff.getMonths(), diff.getDays()); 

的差異應是3年,3個月,10天,但我得到3年,3個月3天

不知道我錯過了什麼,請幫助我。

由於

回答

1

使用構造與3個參數:

Period diff = new Period(endofCentury, now, PeriodType.yearMonthDay());

構造有兩個參數的(from,to)包括周。

所以你的代碼的修改輸出:

Period diff = new Period(endofCentury, now); 
System.out.printf("Difference is %d years, %d months and %d weeks and %d days old", 
       diff.getYears(), diff.getMonths(),diff.getWeeks(), diff.getDays()); 

給出了輸出:

差爲3年,3個月及1周和3天

但帶有指定的持續時間字段(第三個參數):

Period diff = new Period(endofCentury, now, PeriodType.yearMonthDay()); 
System.out.printf("Difference is %d years, %d months and %d weeks and %d days old", 
      diff.getYears(), diff.getMonths(),diff.getWeeks(), diff.getDays()); 

你:

差爲3年,3月0周及10日齡

見:http://joda-time.sourceforge.net/apidocs/org/joda/time/PeriodType.html

+0

感謝@傑羅姆。該解決方案爲我工作。 –