Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8 ZoneOffset - How to get current system UTC offset

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.

like image 412
Allison Burgers Avatar asked Feb 26 '17 12:02

Allison Burgers


People also ask

What is ZoneOffset UTC in Java?

ZoneOffset extends ZoneId and defines the fixed offset of the current time-zone with GMT/UTC, such as +02:00. This means that this number represents fixed hours and minutes, representing the difference between the time in current time-zone and GMT/UTC: LocalDateTime now = LocalDateTime.

How do I make the system default ZoneOffset?

The systemDefault() method of the ZoneOffset class in Java is used to return the system default time-zone. Parameters: This method does not accepts any parameters. Return Value: This method returns the system default time-zone.


2 Answers

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.

like image 86
JodaStephen Avatar answered Sep 19 '22 05:09

JodaStephen


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())
like image 29
Michał Szewczyk Avatar answered Sep 18 '22 05:09

Michał Szewczyk