Skip to content
Advertisement

Converting Time Zone to GMT values in Java 11

We keep time zones of the cities in our config table using ID of Time Zone values as Europe/London, Asia/Tokyo, etc. However, when selecting time zones from the list, user needs to see the GMT values for these time zones and we want to display Display Name of Time Zone Options as (UTC+00:00) Dublin, Edinburgh, Lisbon, London rather than Europe/London. As we know, the GMT values are not fixed and we should make some conversion in order to display the current time zone display value. So, how could I do this in Java?

Advertisement

Answer

Let’s say, you have the ids in a Set<String>, just like ZoneId.getAvailableZoneIds().

You can use a ZoneId in order to create the current moment in time and format its offset as desired:

JavaScript

The first formatter only consider the zone in GMT+/-HH:mm representation and the second one just the literals UTC plus the offset as +/-HH:mm.

The (shortened!) output is

JavaScript

Here’s an idea for your other requirement, listing cities for each offset:

JavaScript

Output (shortened):

JavaScript

Doesn’t look that well this way, but you can apply filters as desired. Maybe remove elements with leading UTC and more, maybe filter out specific continents, whatever.


As methods:

JavaScript

Use the last method in order to get the GMT formats of all available ZoneIds:

JavaScript
User contributions licensed under: CC BY-SA
9 People found this is helpful
Advertisement