2013-11-14 53 views
1

只是爲了驗證這一點:我有這種跛腳和腦死亡方法來計算我當前位置的時區偏移。我想知道當日光節約時間出現問題時我是否需要調整它(目前我們在我的位置有冬令時,CET時區,因此很難驗證)。org.joda.time |日光節省時間(DST)和當地時區偏移

// The local time zone's offset 
private int getLocalOffset() { 
    DateTimeZone defaultZone = DateTimeZone.getDefault(); 
    return defaultZone.getOffset(null)/1000/60/60; 
} 

感謝您的任何提示。

+0

您不應該在小時內使用int來表示本地區域偏移量。許多地方實際上有半小時的抵消(例如:印度)。你不能用你的int表示。喬達時間有幾個毫秒錶示它的原因。 – LordOfThePigs

+0

這是個好主意。我幾乎忘了它。 –

回答

1

通常情況下,喬達時間將自行處理DST,所以您不必擔心。但是,我注意到您正在將null傳遞給getOffset()。考慮到時區偏移量取決於日期,您確實應該傳遞計算偏移量的日期/時間,否則您將得到錯誤的結果。

同樣如我在之前的評論中提到的那樣:請注意,某些時區的偏移量不是整小時數。印度例如是在格林尼治標準時間+5:30

0

是的,沒關係。要驗證它是否正確 - 而不是在DateTime對象中將空通過傳遞給DateTimeZone.getOffset - 將夏令時設置爲夏季的某個時刻,當您知道DST有效時 - 您應該看到偏移值發生變化。

4

時區和夏令時是一場噩夢。你當然不應該自己承擔這個任務。讓喬達時間做重大舉措。

請參閱this answer到相似的問題Using Joda time to get UTC offset for a given date and timezone。類DateTimeZone提供了一個getOffset()方法。

在約達時間2.3

實施例的源代碼在Java中7 ...

// © 2013 Basil Bourque. This source code may be used freely forever by anyone taking full responsibility for doing so. 

org.joda.time.DateTimeZone californiaTimeZone = org.joda.time.DateTimeZone.forID("America/Los_Angeles"); 

org.joda.time.DateTime now = new org.joda.time.DateTime(californiaTimeZone); 
int millisecondOffsetToAddToUtcToGetLocalTime = californiaTimeZone.getOffset(now); 

System.out.println("millisecondOffsetToAddToUtcToGetLocalTime: " + millisecondOffsetToAddToUtcToGetLocalTime); 

// Note the casting to doubles to avoid integer truncation. Time zone offsets are NOT always whole hours. 
System.out.println("Offset in decimal hours: " + (double)millisecondOffsetToAddToUtcToGetLocalTime/1000d/60d/60d); 

當2013-11-20T01運行:03:56.464-08:00 ...

millisecondOffsetToAddToUtcToGetLocalTime: -28800000 
millisecondOffsetToAddToUtcToGetLocalTime in hours: -8.0 

重要對於偏移量,該數字格式-8.0不正確。必須是:

  • -08:00帶冒號和雙位數(填充前導零)。
  • -08與領先的零。