我想获得时区的真实偏移量。
我的问题 :
TimeZone tz = TimeZone.getTimeZone("America/Toronto");
int test = tz.getRawOffset();
test = -18000000
-18000000/1000/3600 = -5
Run Code Online (Sandbox Code Playgroud)
我看到多伦多的时间是 UTC-4。
它在文档中写道,该方法返回原始偏移量。
但我怎样才能得到真正的偏移量呢?
getRawOffset不考虑 DST。它反映的是标准时间。来自文档:
Returns the amount of time in milliseconds to add to UTC to get standard time in this time zone. Because this value is not affected by daylight saving time, it is called raw offset.
Toronto is currently observing daylight saving time (until November 4th) so its current UTC offset is -4 hours, but that's -5 hours "standard" and +1 hour DST.
Now there's an inaccurate assumption there: that a time zone never changes its standard time. java.util.TimeZone is a relatively old and primitive representation; it would be better to use java.time.ZoneId instead, along with the rest of the java.time package.
If you must use java.util.TimeZone, then call getOffset(long) to get the UTC offset at a particular instant in time.