The new Java date-time API provides new leverages for solving this problem.
At the first step, the available time zones IDs can be obtained via the ZoneId class, as follows:
Set<String> zoneIds = ZoneId.getAvailableZoneIds();
At the second step, each time zone ID should be used to create a ZoneId instance. This can be accomplished via the ZoneId.of(String zoneId) method:
ZoneId zoneid = ZoneId.of(current_zone_Id);
At the third step, each ZoneId can be used to obtain the time that is specific to the identified zone. This means that a "lab rats" reference date-time is needed. This reference date-time (without a time zone, LocalDateTime.now()) is combined with the given time zone (ZoneId), via LocalDateTime.atZone(), in order to obtain ZoneDateTime (a date-time that is time-zone aware):
LocalDateTime now = LocalDateTime.now();
ZonedDateTime zdt = now.atZone(ZoneId.of(zone_id_instance));
At the fourth step, the code can exploit ZonedDateTime in order to extract the UTC offset (for example, for Europe/Bucharest the UTC offset is +02:00):
String utcOffset = zdt.getOffset().getId().replace("Z", "+00:00");
The getId() method returns the normalized zone offset ID. The +00:00 offset is returned as the Z character; therefore the code needs to quickly replace Z with +00:00, in order to align with the rest of the offsets, which respect the format +hh:mm or +hh:mm:ss.
Now, let's join these steps into a helper method:
public static List<String> fetchTimeZones(OffsetType type) {
List<String> timezones = new ArrayList<>();
Set<String> zoneIds = ZoneId.getAvailableZoneIds();
LocalDateTime now = LocalDateTime.now();
zoneIds.forEach((zoneId) -> {
timezones.add("(" + type + now.atZone(ZoneId.of(zoneId))
.getOffset().getId().replace("Z", "+00:00") + ") " + zoneId);
});
return timezones;
}
Assuming that this method lives in a DateTimes class, the following code is obtained:
List<String> timezones
= DateTimes.fetchTimeZones(DateTimes.OffsetType.GMT);
Collections.sort(timezones); // optional sort
timezones.forEach(System.out::println);
In addition, an output snapshot is shown, as follows:
(GMT+00:00) Africa/Abidjan
(GMT+00:00) Africa/Accra
(GMT+00:00) Africa/Bamako
...
(GMT+11:00) Australia/Tasmania
(GMT+11:00) Australia/Victoria
...