Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Java 8: how to derive a ZoneId from ZoneOffset

Tags:

java

date

java-8

I was reading the API for the ZoneId class. It states that there are three tipes of ID:

  1. derived from ZoneOffset
  2. offset-style IDs with some form of prefix. Examples:

    ZoneId.of("GMT+2");
    ZoneId.of("UTC");
    ZoneId.of("UT+01:00");
    
  3. region-based. Examples:

    ZoneId.of("Asia/Aden");
    ZoneId.of("Etc/GMT+9");
    ZoneId.of("Asia/Aqtau");
    

But what is the right syntax for the first kind? Documentation says that

[ID from ZoneOffset] consists of 'Z' and IDs starting with '+' or '-'.

What's the combination of String and ZoneOffset object I'm supposed to use to create a ZoneId of the first kind?

like image 581
Luigi Cortese Avatar asked Oct 04 '15 09:10

Luigi Cortese


1 Answers

There are actually two question to be answered here

1) What is the right syntax for the first kind?

This is it:

    ZoneId z;
    z = ZoneId.of("Z"); //for UTC
    z = ZoneId.of("+02:00"); 
    z = ZoneId.of("-02:00"); 

here you can find the complete list

  • Z - for UTC
  • +h
  • +hh
  • +hh:mm
  • -hh:mm
  • +hhmm
  • -hhmm
  • +hh:mm:ss
  • -hh:mm:ss
  • +hhmmss
  • -hhmmss

I wrongly thougt that

'Z' AND IDs starting with '+' or '-'

meant that you always needed a Z prefix (to compose something like Z+02:00). I think OR would be more appropriate.

2) What's the [needed] combination of String and ZoneOffset object?

No combination needed, you can either use a string or a ZoneOffset object:

    ZoneId z;
    z = ZoneId.of("+02:00"); 
    z = ZoneId.of(ZoneOffset.of("+02:00").getId());
like image 161
Luigi Cortese Avatar answered Sep 24 '22 21:09

Luigi Cortese