如何在 Java 中获取时区的 UTC 偏移量?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/33027203/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I get the UTC offset for a timezone in Java?
提问by RainSear
Given a timezone (America/New_York
), how do I go about getting the UTC offset?
给定一个时区 ( America/New_York
),我该如何获取 UTC 偏移量?
I have tried using java.util.TimeZone
but had no luck. I am fine with using Joda Time as well if the solution is viable in that.
我试过使用java.util.TimeZone
但没有运气。如果解决方案可行,我也可以使用 Joda Time。
回答by Monz
The offset for a particular time zone can vary based on the current time because of daylight savings, etc. UTC doesn't have daylight savings, but "America/New_York" will change offsets with the daylight savings switch. Therefore, the offset is a function of boththe current time and the timezone. The answers here give some examples of how to get the current offset:
由于夏令时等原因,特定时区的偏移量可能因当前时间而异。UTC 没有夏令时,但“America/New_York”将通过夏令时开关更改偏移量。因此,偏移量是的函数二者当前时间和时区。这里的答案给出了一些如何获取当前偏移量的示例:
回答by Дмитрий Кулешов
Note: Current offset depends on
注意:电流偏移取决于
- raw tz-offset
- day-savings time (DST) for a CURRENT moment.
- 原始 tz 偏移
- 当前时刻的节时 (DST)。
This is well described in near answer.
这在near answer中有很好的描述。
Useful snippets:
有用的片段:
TimeZone.getTimeZone("Europe/Kiev").getOffset(Instant.now().toEpochMilli());
will give you integer offset in milliseconsString.format("%tz", Instant.now().atZone(ZoneId.of("Europe/Kiev")));
will give you a standardized string representation like "+0300"
TimeZone.getTimeZone("Europe/Kiev").getOffset(Instant.now().toEpochMilli());
将以毫秒为单位为您提供整数偏移量String.format("%tz", Instant.now().atZone(ZoneId.of("Europe/Kiev")));
会给你一个标准化的字符串表示,比如“+0300”