java 8 getting timeZone from zonedLocalTime

Viewed 6386

I am writing a helper method that takes String representation of date and returns TimeZone

for example:

input: 2017-11-02T09:30:00-07:00
output : "America/Los_Angeles"

(Here the input is PST. I am using UTC offset of -7:00)

Here is my method
 public static String getTimeZone(final String date) {
        ZonedDateTime zonedDateTime = ZonedDateTime.parse(date, DateTimeFormatter.ISO_DATE_TIME);

        String timezone = TimeZone.getTimeZone(zonedDateTime.getZone()).getAvailableIDs()[0];
        System.out.println(timezone);
        return timezone;
    }

when I pass in the above date, I get Africa/Abidjan which is totally incorrect.

I prefer "America/Los_Angeles" but atleast something that is correct. Here what I get is totally wrong in the sense, that time in Abidjan and Los_Angeles are very different.

what is the right way to get here?

2 Answers

Here my proposition :

public static String getTimeZone(final String date) {
    final ZonedDateTime zonedDateTime = ZonedDateTime.parse(date,DateTimeFormatter.ISO_DATE_TIME);
    final TimeZone timeZone = TimeZone.getTimeZone(zonedDateTime.getZone());
    return  Arrays.stream(TimeZone.getAvailableIDs(timeZone.getRawOffset())).peek(System.out::println).findFirst().get();
}

Here the output

//America/Boise

TimeZone.getAvailableIDs() is a static method and just returns all the known ids for every zone.

You can use TimeZone.getAvailableIDs(int rawOffset) which returns the ids for a given millisecond offset.

For your example date/time

TimeZone tz = TimeZone.getTimeZone(zonedDateTime.getZone());
for (final String id : TimeZone.getAvailableIDs(tz.getRawOffset())) {
  System.out.println("id " + id);
}

gives:

id America/Boise
id America/Cambridge_Bay
id America/Chihuahua
id America/Creston
id America/Dawson_Creek
id America/Denver
id America/Edmonton
id America/Fort_Nelson
id America/Hermosillo
id America/Inuvik
id America/Mazatlan
id America/Ojinaga
id America/Phoenix
id America/Shiprock
id America/Yellowknife
id Canada/Mountain
id Etc/GMT+7
id MST
id MST7MDT
id Mexico/BajaSur
id Navajo
id PNT
id SystemV/MST7
id SystemV/MST7MDT
id US/Arizona
id US/Mountain
Related