简体   繁体   中英

joda time api behaves differently for two different set of dates

The two different code snippets(with minor change) show some error in calculations by joda time api:

First one: Gives 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");

Gives result : 2 years 5 months 6 days

Second one: Gives incorrect result

Change in snippet : 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");

Gives result : 2 years 5 months 0 days

Is this an error of calculation or am I missing some configuration?

I believe this is because the 7 days are now 1 week. What happens is that the largest possible value of time which will encapsulate the remainder will always be used.

IE 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 what you need is something like:

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

What has happened is that you have rolled a week. I would gather that if you tried "2012,6,13,0,0,0,0" as your inputs, you'd get a ...1 days result.

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM