2016-03-15 47 views
0

請幫助我瞭解爲什麼下面的代碼:Jodatime期產生2開始日期不同,相同的輸出和相同的結束日期

import org.joda.time.DateTime; 
import org.joda.time.Period; 
import org.joda.time.PeriodType; 
import org.joda.time.format.PeriodFormat; 

public class TimeTestFail { 

    public static void main(String[] args) { 
     DateTime jdEnd = new DateTime(2014, 5, 1, 0, 0); 

     DateTime jdStart1 = new DateTime(2013, 5, 31, 0, 0); 

     Period pmd = new Period(jdStart1, jdEnd, PeriodType.yearMonthDayTime()); 

     // prints "period for jdStart1 = 11 months and 1 day" 
     System.out.println("period for jdStart1 = " + pmd.toString(PeriodFormat.getDefault())); 

     DateTime jdStart2 = new DateTime(2013, 5, 30, 0, 0); 
     Period pmd2 = new Period(jdStart2, jdEnd, PeriodType.yearMonthDayTime()); 


     // prints "period for jdStart2 = 11 months and 1 day" (same thing as for the other date!) 
     System.out.println("period for jdStart2 = " + pmd2.toString(PeriodFormat.getDefault())); 

    } 

} 

產生同期產量(11個月零1天)。正如你可以看到我的計算週期的兩倍:

2013-05-31 ----- 2014-05-01 

2013-05-30 ----- 2014-05-01 

在它產生的11個月1天這兩種情況下,這是完整的輸出

period for jdStart1 = 11 months and 1 day 
period for jdStart2 = 11 months and 1 day 

我正在使用jodatime 2.9.2

回答

0

問題:

「請幫助我瞭解爲什麼代碼...」

答:

只需添加11個月後來有一天(以這個順序)的開始日期,和你會觀察到相同的結束日期。

案例a:在2013-05-30添加了11個月之後,您的日期是2014-04-30。然後再增加一天,得到2014-05-01。

案例b:在2013-05-31添加了11個月之後,您的虛擬日期2014-04-31不存在,並且將縮短到最後有效日期2014-04-30。然後再增加一天就會產生2014-05-01。如何添加月份的行爲是documented

相關問題