2013-12-22 191 views
1

我使用下面的代碼來獲得在今年2個日期之間的差異,月,日喬達時期年月日

tenAppDTO.getTAP_PROPOSED_START_DATE()=2009-11-01 
tenAppDTO.getTAP_PROPOSED_END_DATE()=2013-11-29                   
ReadableInstant r=new DateTime(tenAppDTO.getTAP_PROPOSED_START_DATE()); 
ReadableInstant r1=new DateTime(tenAppDTO.getTAP_PROPOSED_END_DATE()); 
Period period = new Period(r, r1); 
period.normalizedStandard(PeriodType.yearMonthDay()); 
years = period.getYears(); 
month=period.getMonths(); 
day=period.getDays(); 
out.println("year is-:"+years+"month is -:"+ month+"days is -:"+ day); 

通過上面的代碼我得到的結果是 - 一年:4月份是 - : 0天 - :0 但實際的結果是每年爲 - 4月份是 - :0天 - 28

請提供一個解決方案

回答

3

您可以嘗試改變

Period period = new Period(r, r1); 

Period period = new Period(r, r1, PeriodType.yearMonthDay()); 

你可以嘗試這樣的:

tenAppDTO.getTAP_PROPOSED_START_DATE()=2009-11-01 
tenAppDTO.getTAP_PROPOSED_END_DATE()=2013-11-29                   
ReadableInstant r=new DateTime(tenAppDTO.getTAP_PROPOSED_START_DATE()); 
ReadableInstant r1=new DateTime(tenAppDTO.getTAP_PROPOSED_END_DATE()); 
Period period = new Period(r, r1, PeriodType.yearMonthDay()); //Change here 
period.normalizedStandard(PeriodType.yearMonthDay()); 
years = period.getYears(); 
month=period.getMonths(); 
day=period.getDays(); 
out.println("year is-:"+years+"month is -:"+ month+"days is -:"+ day); 
+2

非常感謝你! – nakul

+1

@nakul: - 不客氣! –

+0

@RahulTripathi你能解釋**新期間(r,r1,day); **是如何工作的嗎?爲什麼我們需要在其中包含一天? – Keerthivasan

0

即使你拉胡爾已經回答了,我可以提供多一點視覺上吸引人碼(爲兩個問題,答案都有點凌亂):

DateTime date1 = new DateTime(2009, 11, 01, 00, 00); 
DateTime date2 = new DateTime(2013, 11, 29, 00, 00); 
Period period = new Period(date1, date2, PeriodType.yearMonthDay()); 
System.out.println("Y: " + period.getYears() + ", M: " + period.getMonths() + 
     ", D: " + period.getDays()); 
// => Y: 4, M: 0, D: 28 

你需要指定期間類型年 - 月 - 日爲STA ndard型(PeriodType.standard())是基於年 - 月 - - 日-...和指定日期相差一天恰好是4周

Period period = new Period(date1, date2, PeriodType.standard()); 
System.out.println("Y: " + period.getYears() + ", M: " + period.getMonths() + 
     ", W: " + period.getWeeks() + ", D: " + period.getDays()); 
// => Y: 4, M: 0, W: 4, D: 0 
0

您可以使用從Period.ofjava.time.Period

public Period getPeriodForMonthsAndDays(int monthsCount, int daysCount) { 
    return Period.of(0, monthsCount, daysCount); 
}