2015-06-12 45 views
2

我已經把我的系統數據的時間亞洲/加爾各答和它是:在Java 8中沒有得到正確的時區?

Date: 2015-06-12 
Time: 12:07:43.548 

現在我已經用Java編寫下面的程序8

ZoneId paris = ZoneId.of("Europe/Paris"); 
LocalDateTime localtDateAndTime = LocalDateTime.now(); 
ZonedDateTime dateAndTimeInParis = ZonedDateTime.of(localtDateAndTime, paris); 
System.out.println("Current date and time in a particular timezone : " + dateAndTimeInParis ); 

當我運行的代碼,它顯示了以下時間巴黎:

Current date and time in a particular timezone :  

2015-06-12T12:07:43.548+02:00[Europe/Paris] 

上述歐洲/巴黎是亞洲/加爾各答相同。任何人都可以請解釋我在做什麼錯?

更新:我不喜歡使用其他Java包中的類;因爲我聽說這個包java.time有足夠的功能來處理最大日期時間作業,我希望這個包括:)

+0

你可以嘗試先將TimeZone.setDefault設置爲正確的時區。 TimeZone.setDefault(TimeZone.getTimeZone(「<必填時區here>」)); –

+0

日曆calParis = Calendar.getInstance(); calParis.setTimeZone(TimeZone.getTimeZone(「Europe/Paris」)); System.out.println(「巴黎時間:」+ calParis.get(Calendar.HOUR_OF_DAY)+「:」 + calParis.get(Calendar.MINUTE )); –

+0

@Himanshu: 如果我設置它;那麼當我需要更改時區時,我需要一次又一次地重置它。 – fatherazrael

回答

10

A LocalDateTime是一個日期和時間沒有時區。當您創建一個ZonedDateTime對象時,您明確地將時區附加到LocalDateTime

它不會從您的時區轉換到Europe/Paris時區;請注意,LocalDateTime根本沒有時區;它不知道你的意思是Asia/Kolkata

如果你想從加爾各答時間巴黎時間轉換,啓動與使用Asia/Kolkata時區一個ZonedDateTime

// Current time in Asia/Kolkata 
ZonedDateTime kolkata = ZonedDateTime.now(ZoneId.of("Asia/Kolkata")); 

// Convert to the same time in Europe/Paris 
ZonedDateTime paris = kolkata.withZoneSameInstant(ZoneId.of("Europe/Paris")); 

(編輯,感謝JBNizet):如果你只是想「現在」的Europe/Paris時間,你可以這樣做:

ZonedDateTime paris = ZonedDateTime.now(ZoneId.of("Europe/Paris")); 
+4

沒問題。 OP想要的是'ZonedDateTime.now(ZoneId.of(「歐洲/巴黎」))' –

+2

@JBNizet如果你只是想在巴黎時間「現在」,那也可以。 – Jesper

+0

@Jesper:謝謝,讓我試試 – fatherazrael