2012-02-07 86 views
13

要求是簡單地獲取給定時區的當前掛牆時間(包括正確的DST調整)。使用Joda時間獲得給定時區的當前掛牆時間

似乎有一些問題圍繞着這個盤旋,但我似乎無法找到一個直接的答案(在SO,喬達多克或谷歌搜索)與低摩擦的方式獲得牆的時間。這似乎是與給定的輸入(當前UTC時間和所需的TZ)我應該能夠鏈條從約達時間庫幾個方法來實現我想要什麼,但似乎在說的例子來評價+處理偏移的願望/在應用程序代碼轉換 - 我希望儘可能地避免這種情況,只需使用Jodas盡力而爲根據其設定的可用靜態TZ規則。

對於這個問題的目的,讓我們假設我不會使用(基於網絡或其他二進制文件)任何其他第三方服務,究竟什麼是可從JDK和JodaTime庫。

任何指針讚賞。

更新: 這實際上是一個代表我的失敗。我在陽光明媚的有計算基於請求經度UTC偏移,而這顯然是工作,你仍然需要區域信息以獲得正確的DST調整..

double aucklandLatitude = 174.730423; 
int utcOffset = (int) Math.round((aucklandLatitude * DateTimeConstants.HOURS_PER_DAY)/360); 
System.out.println("Offset: " + utcOffset); 

DateTimeZone calculatedDateTimeZone = DateTimeZone.forOffsetHours(utcOffset); 
System.out.println("Calculated DTZ: " + calculatedDateTimeZone); 
System.out.println("Calculated Date: " + new DateTime(calculatedDateTimeZone)); 
System.out.println(); 
DateTimeZone aucklandDateTimeZone = DateTimeZone.forID("Pacific/Auckland"); 
System.out.println("Auckland DTZ: " + aucklandDateTimeZone); 
System.out.println("Auckland Date: " + new DateTime(aucklandDateTimeZone)); 

打印

Offset: 12 
Calculated DTZ: +12:00 
Calculated Date: 2012-02-08T11:20:04.741+12:00 

Auckland DTZ: Pacific/Auckland 
Auckland Date: 2012-02-08T12:20:04.803+13:00 

所以在這裏Auckland, NZ我們在DST期間+12 +13不過。

我的壞。儘管如此,謝謝你的答案,讓我看到了我的錯誤。

回答

17

有你看了DateTime構造:

DateTime(DateTimeZone zone) 

此構造表示指定時區的當前時間的DateTime。

+6

我寧願'DateTime.now(DateTimeZone區)'因爲我覺得它更明顯。 – 2012-07-26 08:36:39

+1

順便說一句,調整時區的呼叫'withZone(myTimeZone)'。 – 2014-06-10 18:52:37

13

如何:

DateTime utc = new DateTime(DateTimeZone.UTC); 
DateTimeZone tz = DateTimeZone.forID("America/Los_Angeles"); 
DateTime losAngelesDateTime = utc.toDateTime(tz); 
+0

正確,但有兩個問題。 (A)不需要通過毫秒的當前時間,Joda-Time在內部爲你做。當你的代碼交給毫秒計數時,這個參數是用於轉換的。 (B)'local'是var name的糟糕選擇,因爲與LocalDate混淆意味着沒有時區。 – 2014-06-10 18:50:39

+0

順便說一下'.forId'應該是'.forID'。 – user2323030 2015-01-25 01:53:02

8

乾淨利落的方法

我發現下面是最乾淨的方法。

DateTime currentTime = DateTime.now(DateTimeZone.UTC); 

這可以讓你的當前時間UTC但是這個值可以被轉換成另一種DateTimeZone或者你可以用不同的DateTimeZone更換DateTimeZone.UTC

使用系統時區

如果你想將它設置爲系統時區,您可以使用此:

DateTime currentTime = DateTime.now(DateTimeZone.getDefault());