为什么 JodaTime 和 Calendar 返回不同的结果

发布于 2024-11-26 08:43:51 字数 432 浏览 1 评论 0原文

为什么这个测试失败:

    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技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

め七分饶幸 2024-12-03 08:43:51

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.

只是偏爱你 2024-12-03 08:43:51

原因有两个:

  1. Joda 有一个基础月份。所以你需要改变这一点。

  2. 日历设计得很糟糕。您没有将秒的毫秒数设置为 0。 cal.set(MILLISECOND, 0)

这是 javadoc

公共最终无效集(int年份,
整月,
整数日期,
int hourOfDay,
分钟,
整数秒)

其中缺少毫秒字段。

Two reasons:

  1. Joda has one based months. So you need to change that.

  2. Calendar is poorly designed. You are not setting the milliseconds of the second to 0. cal.set(MILLISECOND, 0)

Here is the javadoc

public final void set(int year,
int month,
int date,
int hourOfDay,
int minute,
int second)

Which is missing the millisecond field.

别低头,皇冠会掉 2024-12-03 08:43:51

从零开始的符号与从一开始的符号

Zero-based vs. one-based notations

意中人 2024-12-03 08:43:51

我在这里猜测 Joda 的 1997, 01,01 意味着 1997 年 1 月 1 日

但在 Java 日历中,月份的编号范围为 0 - 11,因此 1997,01,01 对于 Java 来说实际上是 2 月 1 日。

更好的方法是使用 --

cal.set(1997, Calendar.JANUARY, 01, 00,00,00);

您还应该重置日历的毫秒数正如@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 --

cal.set(1997, Calendar.JANUARY, 01, 00,00,00);

You should also reset the MILLISECONDS of the Calendar object to 0 as @Amir pointed out.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文