Get timezone of area with country code in Java

孤街醉人 提交于 2021-01-01 02:15:14

问题


I have to pass a message (jms) with timezone info like (America/Los_Angeles) but I have only country name and code. If it possible get timezone info with Java code. Somewhere I read this:

System.out.println(TimeZone.getTimeZone("US"));

But its giving output as

sun.util.calendar.ZoneInfo[id="GMT",offset=0,dstSavings=0,useDaylight=false,transitions=0,lastRule=null]

I am expecting List of "America/Los_Angeles", ...


回答1:


As per the documentation the getTimeZone method returns the specified TimeZone, or the GMT zone if the given ID cannot be understood. There's no TimeZone ID called US hence it gives the GMT zone. If you really want to get all the list of TimeZones available in US, I would suggest you to use the following.

final List<String> timeZonesInUS = Stream.of(TimeZone.getAvailableIDs())
        .filter(zoneId -> zoneId.startsWith("US")).collect(Collectors.toList());



回答2:


The builtin Java classes don't offer this, but ICU's TimeZone class does, and TimeZone.getAvailableIDs("US") provides the correct answer.




回答3:


If I'm understanding correctly, it looks like you just want a list of timezones from a given country. This site has a list of all the countries that have their own code:

https://garygregory.wordpress.com/2013/06/18/what-are-the-java-timezone-ids/

Looking at the API for TimeZones shows that there's no way to grab a list of timezones directly through TimeZone.getTimeZone(). So instead, you probably want to loop through them and just see which ones start with the country name and add them to a list, like so:

public static List<String> GetZones(String country) {
    List<String> zones = new ArrayList<>();

    for (String i : TimeZone.getAvailableIDs()) {
        if (i.startsWith(country)) {
            zones.add(i);
        }
    }
    return zones;

}


来源:https://stackoverflow.com/questions/50498146/get-timezone-of-area-with-country-code-in-java

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