Suzan
Suzan

Reputation: 305

How to get timezone by utc offset?

I have the UTC offset -05:00, I want to get timezone names by offset.

ZoneOffset offset = ZoneOffset.of("-05:00");
System.out.println(offset.getId()); //prints -05:00

I want to get the result like this :

America/Chicago
America/Eirunepe
Etc/GMT+5
Mexico/General 
...

I want time zones that are at offset -05:00 right now (not those that may be at another time of year).

Upvotes: 1

Views: 2961

Answers (3)

Anonymous
Anonymous

Reputation: 86173

First determine when is “right now”: use Instant.now() (if you want a consistent answer, call Instant.now() only once).

Then iterate over all available time zones and include those that are at offset -05:00 right now. First get available time zone IDs as strings from ZoneId.getAvailableZoneIds(). For each get the corresponding ZoneId object from ZoneId.of(String). There are different ways to obtain the offset right now. One is yourZoneId.getRules().getOffset(rightNow) (where rightNow is your Instant). This gives you a ZoneOffset object that you can compare to your offset from the question using .equals(Object).

Upvotes: 1

Ravindra Ranwala
Ravindra Ranwala

Reputation: 21124

Yes you can do it, check this out.

final List<ZoneId> timeZoneByUtc = ZoneId.getAvailableZoneIds().stream().map(ZoneId::of)
        .filter(z -> z.getRules().getOffset(Instant.now()).equals(ZoneOffset.ofHours(-5)))
        .collect(Collectors.toList());

Upvotes: 3

Shaunak Patel
Shaunak Patel

Reputation: 1671

public class Main {

    public static void main(String[] args) {

        TimeZone tz = TimeZone.getTimeZone("GMT-05:00");
        String a[] = TimeZone.getAvailableIDs(tz.getOffset(System.currentTimeMillis()));
        for (int i = 0; i < a.length; i++) {
            System.out.println(a[i]);
        }
    }
}

O/P

America/Atikokan America/Bogota America/Cancun America/Cayman America/Coral_Harbour America/Detroit America/Eirunepe America/Fort_Wayne America/Grand_Turk America/Guayaquil America/Havana ...

Upvotes: 1

Related Questions