Joda time api behaves differently for two different date sets

Two different code fragments (with slight modifications) show some error in the joda api time calculations:

First: gives the correct result

DateTime date1 = new DateTime(2010,1,5, 0, 0, 0, 0); DateTime date2 = new DateTime(2012,6,11, 0, 0, 0, 0); Period age =new Period(date1,date2); System.out.println(age.getYears()+" years "+age.getMonths()+" months "+age.getDays()+" days"); 

Returns: 2 years 5 months 6 days

Second: gives the wrong result

Fragment change : DateTime date2 = new DateTime (2012,6, 12 , 0, 0, 0, 0);

 DateTime date1 = new DateTime(2010,1,5, 0, 0, 0, 0); DateTime date2 = new DateTime(2012,6,12, 0, 0, 0, 0); Period age =new Period(date1,date2); System.out.println(age.getYears()+" years "+age.getMonths()+" months "+age.getDays()+" days"); 

Returns: 2 years 5 months 0 days

Is this a calculation error or am I missing any configuration?

+4
source share
2 answers

I believe this is because 7 days is now 1 week. It happens that the maximum possible time value will always be used, which will encapsulate the remainder.

those. If you have 8 days, this is 1 week and 1 day. If you have 294 days (depending on the start date), this is 1 year, 1 month, 1 week and 1 day. Etc ...

So you need something like:

System.out.println (age.getYears () + "years" + age.getMonths () + "months" + (age.getWeeks () * 7 + age.getDays ()) + "days");

+4
source

What happened is that you drove a week. I would understand that if you try "2012,6,13,0,0,0,0" as your inputs, you will get the result ...1 days .

Add a getWeeks call to make your output cleaner. Change your println to:

 System.out.println(age.getYears()+" years "+age.getMonths()+" months "+age.getWeeks()+" weeks " + age.getDays()+" days"); 
+3
source

All Articles