Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get timezone of area with country code in Java

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

like image 396
Manvi Avatar asked May 23 '18 22:05

Manvi


People also ask

What is TimeZone getDefault ()?

The getDefault() method is used to get the default TimeZone for this host. The source of the default TimeZone may vary with implementation.

Can we get TimeZone from date java?

Be aware that java. util. Date objects do not contain any timezone information by themselves - you cannot set the timezone on a Date object. The only thing that a Date object contains is a number of milliseconds since the "epoch" - 1 January 1970, 00:00:00 UTC.

What are the java TimeZone IDs?

ECT - Europe/Paris. IET - America/Indiana/Indianapolis. IST - Asia/Kolkata. JST - Asia/Tokyo.


3 Answers

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

like image 105
arnt Avatar answered Oct 16 '22 05:10

arnt


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());
like image 36
Ravindra Ranwala Avatar answered Oct 16 '22 04:10

Ravindra Ranwala


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;

}
like image 35
MusicDev Avatar answered Oct 16 '22 05:10

MusicDev