17

I want to get current ZoneOffset of my system.
I tried to do that but I couldn't find a way.
Also, I was looking for a solution but I didn't find any.
Is it possible to do that in Java?

EDIT:
My question is different to this. I would like to know the current system UTC, not how to convert between TimeZone offset representation or TimeZone storing.

Community
  • 1
  • 1
Allison Burgers
  • 175
  • 1
  • 1
  • 6

2 Answers2

33

Your request has two parts:

  • the offset of "my system" - thus you need the system time-zone - ZoneId.systemDefault()
  • the "current" offset - thus you need the current instant - Instant.now()

These are tied together using ZoneRules, to get the following:

ZoneOffset o = ZoneId.systemDefault().getRules().getOffset(Instant.now());

For simplicty, you might want to use OffsetDateTime:

ZoneOffset o = OffsetDateTime.now().getOffset();

This works because OffsetDateTime.now() uses both ZoneId.systemDefault() and Instant.now() internally.

JodaStephen
  • 60,927
  • 15
  • 95
  • 117
27

Yes, it's possible:

ZoneOffset.systemDefault().getRules().getOffset(Instant.now())

or you can replace Instant instance with LocalDateTime instance:

ZoneOffset.systemDefault().getRules().getOffset(LocalDateTime.now())
Michał Szewczyk
  • 7,540
  • 8
  • 35
  • 47
  • 4
    There is a key difference between these two options. The `Instant` version will always give the right answer. The `LocalDateTime` version will give the ["best available offset"](https://docs.oracle.com/javase/8/docs/api/java/time/zone/ZoneRules.html#getOffset-java.time.LocalDateTime-). This is because of DST, where there may be two valid offsets for the `LocalDateTime`, or none. – JodaStephen Mar 16 '17 at 09:13
  • I can confirm that, when both examples are ran, the following happens in Brazil: if ran outside of DST, `-03:00` is returned; if ran when in DST, `-02:00` is returned. Tested by changing the system's date. – GuiRitter May 13 '19 at 16:14