Joda期间年月日

时间:2013-12-22 07:01:45

标签: java jodatime

我正在使用以下代码来区分年,月,日中的两个日期

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 个答案:

答案 0 :(得分: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);

答案 1 :(得分:0)

即使Rahul已经回答,我也可以提供更具视觉吸引力的代码(因为问题和答案都有点混乱):

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

您需要将期间类型指定为 year-month-day ,因为标准类型(PeriodType.standard())基于年 - 月 - -day -... ,指定日期的日差恰好 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

答案 2 :(得分:0)

您可以使用Period.of

中的java.time.Period
public Period getPeriodForMonthsAndDays(int monthsCount, int daysCount) {
    return Period.of(0, monthsCount, daysCount);
}
相关问题