java.time
Instant now = Instant.now();
ZoneOffset deviceOffset = now.atZone(ZoneId.systemDefault()).getOffset();
ZoneOffset russiaOffset = now.atZone(ZoneId.of("Europe/Moscow")).getOffset();
int diffSeconds = deviceOffset.getTotalSeconds() - russiaOffset.getTotalSeconds();
Duration diff = Duration.ofSeconds(diffSeconds);
System.out.format(Locale.getDefault(),
"Current offset between device time and Moscow time: %+03d%02d%n",
diff.toHours(), diff.toMinutesPart());
Running the above today in Europe/Copenhagen time zone I got:
Current offset between device time and Moscow time: -0100
Since Denmark is currently on summer time (DST) and therefore at offset +0200, and Moscow is at +0300 (all year), this output is correct.
“Russia time” is ambiguous since Russia is using 11 different time zone. There’s a link to a list at the bottom. You mentioned MSK, so I assumed you meant Moscow time. You shouldn’t rely on three or four letter time zone abbreviations, though, at least not in your code. While MSK may be unambiguous, the abbreviations are not standardized and very many of them ambiguous. Instead give time zone as Europe/Moscow (or Asia/Srednekolymsk, etc.).
The toMinutesPart
method I am using was introduced in Java 9. For Java 6 through 8 you need to subtract the hours from the duration and then use toMinutes
.
Why didn’t your approach work?
Pattern letter Z
in a formatter always gives you offset from UTC. So you cannot use it for obtaining offset from Moscow time (or any other time).
As an aside consider throwing away the long outmoded and notoriously troublesome DateFormat
and SimpleDateFormat
and equally outdated friends Date
and Calendar
. java.time
, the modern Java date and time API is so much nicer to work with.
Links