VinodKhade
VinodKhade

Reputation: 147

What is the Zone Id for GMT in Java 8

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 ??

Upvotes: 7

Views: 20825

Answers (3)

Anonymous
Anonymous

Reputation: 86280

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

Upvotes: 2

Arvind Kumar Avinash
Arvind Kumar Avinash

Reputation: 79075

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

Upvotes: 4

deHaar
deHaar

Reputation: 18568

It's ZoneId.of("UTC")...

Here's evidence:

public static void main(String[] args) {
    // define the ZoneId
    ZoneId utc = ZoneId.of("UTC");
    // get the current date and time using that zone
    ZonedDateTime utcNow = ZonedDateTime.now(utc);
    // define a formatter that uses O for GMT in the output
    DateTimeFormatter gmtStyleFormatter = DateTimeFormatter
                                            .ofPattern("uuuu-MM-dd'T'HH:mm:ss.SSS O");
    // and print the datetime using the default DateTimeFormatter and the one defined above
    System.out.println(utcNow + " == " + utcNow.format(gmtStyleFormatter));
}

output (some moments ago):

2020-09-16T08:02:34.717Z[UTC] == 2020-09-16T08:02:34.717 GMT

Getting the total zone offset in seconds of this zone by

utc.getRules().getOffset(Instant.now()).getTotalSeconds();

will result in 0, because this zone has no offset.

Upvotes: 1

Related Questions