2014-01-16 110 views
0

我有一些代碼女巫使用日曆將Joda-DateTime轉換爲java.util.Date。Calendar.getTime()返回不同的日期對象

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評價這段代碼

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

在IntelliJ IDEA的tryed,並返回不同的日期。差異以毫秒爲單位。
我的操作系統是Windwos。
JDK 1.7.0_25

回答

1

添加如下一行:

cal.set(Calendar.MILLISECOND, 0); 

將設置毫秒值。該API文檔指定字段如下:

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

所以它不提供粒度設置millisconds。

旁註:

如果您使用的是Java日期庫籤Jodatime:http://www.joda.org/joda-time/它的好多了!

+0

現在我明白了...當獲取日曆的實例時,它已經與當前時間一起使用。當設置年份,月份等。 MILLISECOND從當前日期開始...... –

相關問題