0

I am trying to get the difference between the two dates using joda time, but somehow I am not able to get the exact difference.

        LocalDate endofCentury = new LocalDate(2014, 01, 01);

        LocalDate now = LocalDate.now(); //2017-04-11

        Period diff = new Period(endofCentury, now); 

        System.out.printf("Difference is %d years, %d months and %d days old", 
                            diff.getYears(), diff.getMonths(), diff.getDays());

The difference should come as 3 years, 3 months, 10 days but I am getting 3 years, 3 months and 3 days.

Not sure what I am missing, please help me out.

Thanks

Hiten Rastogi
  • 152
  • 4
  • 15

1 Answers1

1

Use the constructor with 3 parameters:

Period diff = new Period(endofCentury, now, PeriodType.yearMonthDay());

The constructor with 2 parameters (from,to) includes weeks.

So a modified output of your code:

Period diff = new Period(endofCentury, now);
System.out.printf("Difference is %d years, %d months and %d weeks and %d days old",
                diff.getYears(), diff.getMonths(),diff.getWeeks(), diff.getDays());

gives the output:

Difference is 3 years, 3 months and 1 weeks and 3 days old

but with specified duration fields (3rd parameter):

Period diff = new Period(endofCentury, now, PeriodType.yearMonthDay());
System.out.printf("Difference is %d years, %d months and %d weeks and %d days old",
            diff.getYears(), diff.getMonths(),diff.getWeeks(), diff.getDays());

you get:

Difference is 3 years, 3 months and 0 weeks and 10 days old

see: http://joda-time.sourceforge.net/apidocs/org/joda/time/PeriodType.html

Jérôme
  • 1,254
  • 2
  • 20
  • 25