Search code examples
datedatetimejava-8localdatezoneddatetime

java 8 getting timeZone from zonedLocalTime


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?


Solution

  • 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