時區和夏令時是一場噩夢。你當然不應該自己承擔這個任務。讓喬達時間做重大舉措。
請參閱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
與領先的零。
您不應該在小時內使用int來表示本地區域偏移量。許多地方實際上有半小時的抵消(例如:印度)。你不能用你的int表示。喬達時間有幾個毫秒錶示它的原因。 – LordOfThePigs
這是個好主意。我幾乎忘了它。 –