简体   繁体   English

joda time api对于两组不同的日期表现不同

[英]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: 两个不同的代码片段(略有变化)在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 结果: 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); 变化在代码段 :日期时间日期2 =新日期时间(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 给出结果: 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. 我相信这是因为7天现在是1周。 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. IE如果你有8天,这是1周1天。 If you have 294 days (depending on the start date), this is 1 year, 1 month, 1 week, and 1 day. 如果您有294天(取决于开始日期),则为1年,1个月,1周和1天。 Etc... 等等...

So what you need is something like: 所以你需要的是:

System.out.println(age.getYears()+" years "+age.getMonths()+" months "+ (age.getWeeks()*7 + age.getDays()) +" days"); 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. 如果你尝试“2012,6,13,0,0,0,0”作为你的输入,我会得到一个...1 days结果。

Add a call to getWeeks to make your output cleaner. 添加对getWeeks的调用以使输出更清晰。 Change your println to: 将您的println更改为:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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