我有一些代码使用Calendar将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实例之间存在差异。
我使用代码framgent评估此代码
尝试了Intellij IdeaCalendar cal = Calendar.getInstance();
cal.set(2014,3,18,14,44,32);
cal.getTime()
并返回不同的日期。差异以毫秒为单位
我的操作系统是Windwos
jdk 1.7.0_25
答案 0 :(得分:1)
添加以下行:
cal.set(Calendar.MILLISECOND, 0);
将设置毫秒值。 API文档指定字段如下:
public final void set(int year, int month, int date, int hourOfDay, int minute, int second)
因此它不提供设置毫秒的粒度。
旁注:
如果你使用Java Date libs checkout Jodatime:http://www.joda.org/joda-time/它好多了!