nakul
nakul

Reputation: 533

Joda Period in year month day

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

Upvotes: 1

Views: 1555

Answers (3)

Piotr Fryga
Piotr Fryga

Reputation: 556

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

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

Upvotes: 0

Pavel Horal
Pavel Horal

Reputation: 18194

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

Upvotes: 0

Rahul Tripathi
Rahul Tripathi

Reputation: 172448

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

Upvotes: 3

Related Questions