How to get timezone by utc offset?

为君一笑 提交于 2020-06-17 03:03:33

问题


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).


回答1:


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());



回答2:


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).

Happy coding.




回答3:


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



来源:https://stackoverflow.com/questions/51045064/how-to-get-timezone-by-utc-offset

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!