2013-12-22 192 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); 
}