HashTags
HashTags

Reputation: 105

List of Time Zones in Java

I am using below code to generate a time zone list with Offset.

public static List<String> TimeZonesCollectionUTC(OffsetType type)
{
    List<String> timezonesList = new ArrayList<>();
    Set<String> zoneIds = ZoneId.getAvailableZoneIds();
    LocalDateTime now = LocalDateTime.now();
    zoneIds.forEach((zoneId) ->
    {
        timezonesList.add("(" + type + now.atZone(ZoneId.of(zoneId))
                .getOffset().getId().replace("Z", "+00:00") + ") " + zoneId);
    });
    return timezonesList;
}

The issue is it provides me 600+ time zones. But expectation is to get a user friendly time zone list with less number of list or group it on some rules. Need some help here to create a custom list of time zone in Java with daylight saving also taken care TIA

Upvotes: 1

Views: 1994

Answers (1)

Sweeper
Sweeper

Reputation: 271820

You can group the timezones by their current offsets. The user would choose their current offset first, and then all the timezones that currently have that offset would be shown.

var timezoneGroups = ZoneId.getAvailableZoneIds().stream()
        .map(ZoneId::of)
        .collect(Collectors.groupingBy(x -> x.getRules().getOffset(Instant.now())));

Alternatively, group by getStandardOffset(Instant.now()) if you think your users are going to be more familiar with those.

This gives you a Map<ZoneOffset, List<ZoneId>>. Here is an example of printing it to the command line:

// sort the offsets first...
timezoneGroups.entrySet().stream().sorted(Map.Entry.comparingByKey())
    .forEach(entry -> {
        System.out.println(entry.getKey());
        for (var zone: entry.getValue()) {
            System.out.print("    ");
            System.out.println(zone.getId());
        }
    });

Example output:

...
-01:00
    Etc/GMT+1
    Atlantic/Cape_Verde
    Atlantic/Azores
    America/Scoresbysund
-02:00
    Etc/GMT+2
    America/Noronha
    Brazil/DeNoronha
    Atlantic/South_Georgia
-03:00
    America/Miquelon
    America/Argentina/Catamarca
    America/Argentina/Cordoba
    America/Araguaina
    America/Argentina/Salta
...

Upvotes: 3

Related Questions