We can easily get the millisecond offset of a TimeZone
with only a TimeZone
instance and System.currentTimeMillis()
. Then we can convert from milliseconds to any time unit of choice using the TimeUnit
class.
Like so:
public static int getOffsetHours(TimeZone timeZone) {
return (int) TimeUnit.MILLISECONDS.toHours(timeZone.getOffset(System.currentTimeMillis()));
}
Or if you prefer the new Java 8 time API
public static ZoneOffset getOffset(TimeZone timeZone) { //for using ZoneOffsett class
ZoneId zi = timeZone.toZoneId();
ZoneRules zr = zi.getRules();
return zr.getOffset(LocalDateTime.now());
}
public static int getOffsetHours(TimeZone timeZone) { //just hour offset
ZoneOffset zo = getOffset(timeZone);
TimeUnit.SECONDS.toHours(zo.getTotalSeconds());
}