簡體   English   中英

為什么UTC時區為Java中的System.currentTimeMillis提前了時間?

[英]Why UTC timezone giving ahead time for System.currentTimeMillis in Java?

我從UnixOnstamp格式的RubyOnRails Web服務獲取當前時間(即,從1970年1月1日開始的秒數),服務器上的時區為UTC

在Java中,我試圖將本地當前時間轉換為UTC時間 但是每次它都會提前6分鍾以上 我想獲取UTC當前時間與服務返回時間之間的差額。 我的Java代碼是-

SimpleDateFormat sdf = new SimpleDateFormat("dd-MM-yyyy hh:mm:ss");
Date utc_current = new Date(System.currentTimeMillis());
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
long serverTime = 1424936268000L;
long resTime = sdf.getCalendar().getTimeInMillis() - serverTime;
System.out.println("Time Diff : " + resTime);

其中serverTime是我從Web服務獲取的時間。 並且resTime的值顯示為負值,大約為6分鍾以上。

所以我的問題是,為什么UTC時區為System.currentTimeMillis提前了時間?

請幫助我解決此問題。

與@JB Nizet的注釋中的假設相反,表達式sdf.getCalendar().getTimeInMillis()System.currentTimeMillis()不等效。 證明:

SimpleDateFormat f = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss");
System.out.println("date via System.currentTimeMillis()=" + f.format(utc_current));
System.out.println("date via sdf.getCalendar()=" + f.format(new Date(resTime)));

輸出:

date via System.currentTimeMillis()=2015-02-26T12:19:09
date via sdf.getCalendar()=1889-12-31T04:41:21

如果您仔細研究SimpleDateFormatDateFormat的源代碼,則會在初始化部件代碼中找到類似以下內容的代碼:

private void initializeDefaultCentury() {
    calendar.setTimeInMillis(System.currentTimeMillis());
    calendar.add( Calendar.YEAR, -80 );
    parseAmbiguousDatesAsAfter(calendar.getTime());
}

結論是嚴格避免在 DateFormat -object上使用getCalendar()方法 它僅用作內部可變對象,用於內部格式和解析處理。 很難說通過這種方式您將真正獲得什么。 而是直接使用System.currentTimeMillis()將本地時間與服務器時間進行比較。

另一個問題是您使用的模式。 “ dd-MM-yyyy hh:mm:ss”可能不正確,因為它使用半天的時鍾時間(范圍1-12),但是缺少am / pm的信息。 最好使用圖案符號HH。 檢查Web服務的文檔以獲取正確的格式。

確保服務器和客戶端計算機上的時鍾同步。 這6分鍾可能只是兩者之間的偏移。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM