【问题标题】:Calendar.getTime() return different Date objectsCalendar.getTime() 返回不同的 Date 对象
【发布时间】:2014-01-16 15:37:08
【问题描述】:

我有一些使用日历将 Joda-DateTime 转换为 java.util.Date 的代码。

 Calendar cal = Calendar.getInstance(zone.toTimeZone());
 DateTime zonedDT = internal.toDateTime(zone);
 // Due to JDK and Joda-Time both have time zone implementations and these differ in accuracy.
 // Joda-Time's implementation is generally more up to date and thus more accurate - for example JDK1.3 has no historical data.
 // The effect of this is that the field values of the Calendar may differ from those of this object, even though the millisecond value is the same.
 // Most of the time this just means that the JDK field values are wrong, as our time zone information is more up to date
 // That's why we should manually set date,year, time to calendar
 cal.set(zonedDT.getYear(), zonedDT.getMonthOfYear() - 1, zonedDT.getDayOfMonth(), zonedDT.getHourOfDay(), zonedDT.getMinuteOfHour(), zonedDT.getSecondOfMinute());
 return cal.getTime();

问题在于以这种方式创建的 Date 实例之间存在以毫秒为单位的差异。

我已经在 Intellij Idea 中尝试使用代码框架评估此代码

Calendar cal = Calendar.getInstance();
cal.set(2014,3,18,14,44,32);
cal.getTime()

它返回不同的日期。差异以毫秒为单位。
我的操作系统是 Windwos。
jdk 1.7.0_25

【问题讨论】:

    标签: java calendar jodatime


    【解决方案1】:

    添加一行如下:

    cal.set(Calendar.MILLISECOND, 0);
    

    将设置毫秒值。 API 文档指定字段如下:

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

    因此它不提供设置毫秒数的粒度。

    旁注:

    如果您使用 Java 日期库结帐 Jodatime:http://www.joda.org/joda-time/ 它好多了!

    【讨论】:

    • 现在我明白了......当获取日历实例时,它已与当前时间同步。并在设置年、月等时。 MILLISECOND 取自当前日期...
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2010-09-14
    • 2016-11-19
    • 1970-01-01
    • 2021-09-05
    • 1970-01-01
    相关资源
    最近更新 更多