3

I have a list of time zones that I want the user to choose from. So, I thought I can just call java.time.ZoneId.getAvailableZoneIds() and use the method getDisplayName on them. This results in a lot of duplicate entries like

Central European Time

Even if I add the time zone offset they are not unqiue. However, the ID of a ZoneId distinguishes the entries but how can I localize them? The IDs are always in English like

Europe/Rome

Steffen Harbich
  • 2,639
  • 2
  • 37
  • 71

1 Answers1

7

It's possible to get a localized version of the display name by calling getDisplayName on a ZoneId instance. That would require iteration over the result of getAvailableZoneIds():

ZoneId.getAvailableZoneIds().stream()
        .map(ZoneId::of)
        .map(zid -> zid.getDisplayName(TextStyle.FULL, Locale.GERMAN))
        .distinct()
        .forEach(System.out::println);

Note the TextStyle argument to change the size of each zone's title and the .distinct() method to get unique results.

Manos Nikolaidis
  • 21,608
  • 12
  • 74
  • 82
  • Yes, I could do that but does that really allow the user to pick the right time zone? I mean, are the offsets always the same for time zones with the same display name? – Steffen Harbich Nov 02 '17 at 11:02
  • 1
    @SteffenHarbich Yes timezone name allows picking the right timezone. But the offset changes twice a year if daylight saving is observed. That's why you [need a date/instant to convert ZoneId to ZoneOffset](https://stackoverflow.com/q/32626733/1413133) – Manos Nikolaidis Nov 02 '17 at 11:33
  • Yes, you will still need to decide how you want to handle `ZoneId`s that translate to the same display name in your langauge. I am thinking one option is to add the ID after each, for example “Central European Time - Europe/Rome” and “Central European Time - Europe/Oslo”. Not the most beautiful solution, but I think it should be navigable for the user. – Ole V.V. Nov 02 '17 at 17:43
  • 2
    @OleV.V. this is an option but you have the difference in language then. So if your user is German then an item like "Zentraleuropäische Zeit - Europe/Rome" would be shown, mixing German and the English zone ID. – Steffen Harbich Nov 03 '17 at 07:56
  • I stick to that solution because there is none better for now. However, there is one difference with my implementation. I included the zone offset before making the list distinct to support zone IDs with same display name but different offset. – Steffen Harbich Nov 08 '17 at 15:04
  • 2
    I've found the locale support to be limited. For instance: `ZoneId.of("Asia/Tokyo").getDisplayName(TextStyle.FULL, Locale.forLanguageTag("jp"))` produces "Japan Time" – chaserb Nov 16 '20 at 15:38