我正在使用 Java 中的 ZonedDateTime 库来检索标准时区列表(Olson 时区数据库)之外的任何时区的 UTC 偏移量。
这是我的简单代码。
import java.time.ZoneId;
import java.time.ZonedDateTime;
public class HelloWorld{
public static void main(String []args){
displayUtcOffset("Europe/Istanbul");
displayUtcOffset("America/Caracas");
}
public static void displayUtcOffset(String olsonId){
ZonedDateTime zonedDateTime = ZonedDateTime.now(ZoneId.of(olsonId));
float utcOffset = zonedDateTime.getOffset().getTotalSeconds()/3600f;
System.out.println("For "+olsonId+", UTC"+utcOffset);
}
}
这些的输出是,
For Europe/Istanbul, UTC2.0
For America/Caracas, UTC-4.5
正如我们所见,加拉加斯的 UTC 偏移量是正确的,但伊斯坦 boolean 的 UTC 偏移量实际上是 +3,但它给出的输出为 +2,这是不正确的。 这个 java 库的工作方式有什么变化吗?或者是否有更可靠的库用于将 olson Id 转换为 UTC 偏移量?
最佳答案
您考虑了夏令时吗?例如,当您检查夏天的时间时,如下所示:
public static void displayUtcOffset(String olsonId){
ZonedDateTime zonedDateTime = ZonedDateTime.of(2017, 7, 15, 1, 1, 11, 1, ZoneId.of(olsonId));
float utcOffset = zonedDateTime.getOffset().getTotalSeconds()/3600f;
System.out.println("For "+olsonId+", UTC"+utcOffset);
}
输出与您的预期一致:
For Europe/Istanbul, UTC3.0
For America/Caracas, UTC-4.5
关于java - ZonedDateTime 给出不正确的 UTC 偏移值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41601967/