Java Date得到真正的偏移量



我想获取时区的实际偏移量。

我的问题 :

TimeZone tz = TimeZone.getTimeZone("America/Toronto");
int test = tz.getRawOffset();
test = -18000000
-18000000/1000/3600 = -5 

或者如果我去 https://www.google.fr/search?q=horaire+toronto&oq=horaire+toro&aqs=chrome.1.69i57j0l5.3311j0j7&sourceid=chrome&ie=UTF-8

我看到多伦多在UTC-4上。

它写在文档上,该方法返回 brut 偏移量。

但是我怎样才能得到真正的偏移量呢?

>getRawOffset不考虑DST。它反映标准时间。从文档中:

返回要添加到 UTC 以获取此时区的标准时间的时间量(以毫秒为单位(。由于此值不受夏令时的影响,因此称为原始偏移量。

多伦多目前正在观察夏令时(直到 11 月 4 日(,因此其当前的 UTC 偏移量为 -4 小时,但这是 -5 小时的"标准"和 +1 小时的 DST。

现在有一个不准确的假设:时区永远不会改变其标准时间。java.util.TimeZone是一个相对古老和原始的表示;最好改用java.time.ZoneId,以及java.time包的其余部分。

如果必须使用java.util.TimeZone,则调用getOffset(long)以获取特定时刻的 UTC 偏移量。

java.time

java.utilAPI 已过时且容易出错。建议完全停止使用它,并切换到现代日期时间 API*

使用java.time的解决方案,现代日期时间 API:

import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.time.ZonedDateTime;
public class Main {
public static void main(String[] args) {
ZoneId zoneId = ZoneId.of("America/Toronto");
LocalDateTime ldtDstOn = LocalDateTime.of(LocalDate.of(2018, Month.OCTOBER, 22), LocalTime.MIN);
LocalDateTime ldtDstOff = LocalDateTime.of(LocalDate.of(2018, Month.NOVEMBER, 22), LocalTime.MIN);
// Using ZonedDateTime
ZoneOffset offsetDstOn = ZonedDateTime.of(ldtDstOn, zoneId).getOffset();
// Alternatively, using ZoneId#getRules
ZoneOffset offsetDstOff = zoneId.getRules().getOffset(ldtDstOff);
System.out.println(offsetDstOn);
System.out.println(offsetDstOff);
}
}

输出:

-04:00
-05:00

在线演示

验证加拿大安大略省多伦多2018的时钟更改

要了解有关现代日期-时间 API*的更多信息,请访问跟踪:日期时间


* 出于任何原因,如果你必须坚持使用 Java 6 或 Java 7,你可以使用ThreeTen-Backport,它将大部分java.time功能向后移植到 Java 6 和 7。如果您正在为 Android 项目工作,并且您的 Android API 级别仍然不符合 Java-8,请查看通过脱糖提供的 Java 8+ API 和如何在 Android Project 中使用 ThreeTenABP。

不要使用 getRawOffset

用途 :tz.getOffset(new Date().getTime()) / 1000 / 3600

最新更新