我在欧洲/布鲁塞尔
有两个时间戳1498329000000
和1485282600000
-
其中第一个存在于夏令时,第二个存在于非夏令时
如何获取与 UTC
的正偏移或负偏移(差值)?即 1 小时或 2 小时,基于 DST
。
最佳答案
使用java.time
-API,这非常简单:
public static ZoneOffset getZoneOffset(long epochMillis, String zoneName) {
Instant instant = Instant.ofEpochMilli(epochMillis);
ZonedDateTime zonedDateTime = instant.atZone(ZoneId.of(zoneName));
return zonedDateTime.getOffset();
}
public static void main(String[] args) {
System.out.println(getZoneOffset(1498329000000l, "Europe/Brussels")); // +02:00
System.out.println(getZoneOffset(1485282600000l, "Europe/Brussels")); // +01:00
}
<小时/>
另请查看类(class) ZoneRules
其中有一些有用的方法来处理时区和夏令时 (DST):
boolean isDaylightSavings(Instant instant)
Checks if the specified instant is in daylight savings.
This checks if the standard offset and the actual offset are the same for the specified instant. If they are not, it is assumed that daylight savings is in operation.
This default implementation compares the actual and standard offsets.
Parameters:
instant
- the instant to find the offset information for, not null, but null may be ignored if the rules have a single offset for all instantsReturns:
the standard offset, not nullDuration getDaylightSavings(Instant instant)
Gets the amount of daylight savings in use for the specified instant in this zone.
This provides access to historic information on how the amount of daylight savings has changed over time. This is the difference between the standard offset and the actual offset. Typically the amount is zero during winter and one hour during summer. Time-zones are second-based, so the nanosecond part of the duration will be zero.
This default implementation calculates the duration from the actual and standard offsets.
Parameters:
instant
- the instant to find the daylight savings for, not null, but null may be ignored if the rules have a single offset for all instantsReturns:
the difference between the standard and actual offset, not nullZoneOffsetTransition nextTransition(Instant instant)
Gets the next transition after the specified instant.
This returns details of the next transition after the specified instant. For example, if the instant represents a point where "Summer" daylight savings time applies, then the method will return the transition to the next "Winter" time.
Parameters:
instant
- the instant to get the next transition after, not null, but null may be ignored if the rules have a single offset for all instantsReturns:
the next transition after the specified instant, null if this is after the last transition
要获取 ZoneRules
,您可以使用:
ZoneRules rules = ZoneId.of("Europe/Brussels").getRules();
关于java - 如何在JAVA中获取时间戳的偏移量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48438079/