Joda Period in year month day

瘦欲@ 提交于 2019-12-13 02:16:45

问题


i am using following code to get difference between 2 dates in year,month,day

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);

by using above code i get the result year is-:4 month is -:0 days is -:0 but actual result is year is-:4 month is -:0 days is -:28

Please provide a solution


回答1:


You may try to change

Period period = new Period(r, r1); 

with

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

You may try like this:

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:


Even thou Rahul already answered, I can provide a bit more visually appealing code (as both the question and the answer are a bit messy):

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

You need to specify period type as year-month-day as the standard type (PeriodType.standard()) is based on year-month-week-day-... and the day difference for the specified dates is exactly 4 weeks:

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



回答3:


You can use Period.of from java.time.Period

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


来源:https://stackoverflow.com/questions/20727066/joda-period-in-year-month-day

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!