为什么 JodaTime 和 Calendar 返回不同的结果
为什么这个测试失败:
DateTime dateTime = new DateTime(1997,01,01,00,00,00,00, DateTimeZone.UTC);
long jodaMills = dateTime.getMillis();
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.set(1997,01,01,00,00,00);
long calMills = cal.getTimeInMillis();
Assert.assertEquals(jodaMills, calMills);
我得到的结果是: 预计:852076800000 实际:854755200964
他们不应该是相同的数字吗?
Why does this test fail:
DateTime dateTime = new DateTime(1997,01,01,00,00,00,00, DateTimeZone.UTC);
long jodaMills = dateTime.getMillis();
Calendar cal = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
cal.set(1997,01,01,00,00,00);
long calMills = cal.getTimeInMillis();
Assert.assertEquals(jodaMills, calMills);
I get a result of:
Expected :852076800000
Actual :854755200964
Shouldn't they be the same number?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
![扫码二维码加入Web技术交流群](/public/img/jiaqun_03.jpg)
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
Calendar 的月份从零开始,JodaTime 月份字段从 1 开始。
因此,在 JodaTime 中,一月是第 1 个月,但在 Calendar 中,一月是第 0 个月。
因此,在您的示例中,您要比较 1 月 1 日到2 月 1 日,因此价值观有所不同。
毫秒之间也存在差异,因为 JodaTime 被设置为零,但 Calendar 对象却没有。
Calendar has zero based months, and JodaTime months fields starts at 1.
So, in JodaTime, January is month 1, but in Calendar, January is month 0.
Therefore, in your example you are comparing January 1st to February 1st, hence the difference in values.
There is also a difference in milliseconds, as the JodaTime is being set to zero, but the Calendar object is not.
原因有两个:
Joda 有一个基础月份。所以你需要改变这一点。
日历设计得很糟糕。您没有将秒的毫秒数设置为 0。
cal.set(MILLISECOND, 0)
这是 javadoc
其中缺少毫秒字段。
Two reasons:
Joda has one based months. So you need to change that.
Calendar is poorly designed. You are not setting the milliseconds of the second to 0.
cal.set(MILLISECOND, 0)
Here is the javadoc
Which is missing the millisecond field.
从零开始的符号与从一开始的符号
Zero-based vs. one-based notations
我在这里猜测 Joda 的
1997, 01,01
意味着 1997 年 1 月 1 日。但在 Java 日历中,月份的编号范围为 0 - 11,因此 1997,01,01 对于 Java 来说实际上是 2 月 1 日。
更好的方法是使用 --
您还应该重置日历的毫秒数正如@Amir 指出的那样,反对 0。
I'm going to guess here that
1997, 01,01
for Joda means January 1st, 1997.But in Java Calendar, months are numbered from 0 - 11, so 1997,01,01 for Java is actually February 1st.
A better approach is to use --
You should also reset the MILLISECONDS of the Calendar object to 0 as @Amir pointed out.