Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What is the Zone Id for GMT in Java 8

Tags:

I want to get the difference in seconds to find whether the system timezone is ahead or behind the remote timezone. Here the remote timezone value is "GMT" which i fetch from Database. It could be "US/Eastern", which i convert to "America/New_York". But for GMT, im getting ERROR.

ZoneId.systemDefault().getRules().getOffset(Instant.now()).getTotalSeconds() 
    - ZoneId.of("GMT").getRules().getOffset(Instant.now()).getTotalSeconds()

But it gives the following error,

Exception in thread "main" java.time.DateTimeException: Invalid ID for ZoneOffset, invalid format: 
    at java.time.ZoneOffset.of(Unknown Source)
    at java.time.ZoneId.of(Unknown Source)
    at java.time.ZoneId.of(Unknown Source)

How to resolve this error ? What to use in place of GMT ??

like image 290
VinodKhade Avatar asked Sep 16 '20 07:09

VinodKhade


2 Answers

Use Etc/UTC

import java.time.Instant;
import java.time.ZoneId;

public class Main {
    public static void main(String args[]) {
        System.out.println(ZoneId.of("Etc/UTC").getRules().getOffset(Instant.now()).getTotalSeconds());
    }
}

Output:

0
like image 152
Arvind Kumar Avinash Avatar answered Sep 30 '22 20:09

Arvind Kumar Avinash


The official answer is:

Etc/GMT

It’s the same as the Etc/UTC suggested in the other answers except for the name.

For the sake of completeness there are a number of aliases for the same, many of them deprecated, not all. You can find them in the link.

And I am not disagreeing with the comments telling you to prefer UTC. I just wanted to answer the question as asked.

For your case you should not need to ask at all though. ZoneId.of("GMT").getRules().getOffset(Instant.now()).getTotalSeconds() should always yield 0, so there is no need to subtract anything. I would either insert a comment why I don’t or subtract a well-named constant with the value 0.

Link: List of tz database time zones

like image 27
Ole V.V. Avatar answered Sep 30 '22 20:09

Ole V.V.