Using City names (example. Abu Dhabi, Sydney,Dhaka,Paris etc.) need to find local time zone. 2 digit country code can be used

1 Answers

Ole V.V. On

For a solution covering all thinkable city names this will require a database containing cities and their corresponding time zones. It will be further complicated by the fact that cities with the same name exist, so you may have ambiguous input. For example, by Paris I suppose you intended the capital and largest city of France, Europe, but towns called Paris exist in other places too. I don’t know if a suitable database exists, you may search.

I can get you close, though, with what is built into Java. Time zones have IDs in the form region/city, for example Australia/Sydney and Asia/Dubai. The city used in naming the time zone is the largest populated area of the time zone, so even in the case where a country or state is only one time zone, the city needs not be the capital. But if the city coincides, we can find the zone.

    Set<String> zids = ZoneId.getAvailableZoneIds();

    String[] cityNames = { "Abu Dhabi", "Dubai", "Sydney", "Dhaka", "Paris", "Indianapolis", "São Tomé" };
    for (String cityName : cityNames) {
        String tzCityName = Normalizer.normalize(cityName, Normalizer.Form.NFKD)
                .replaceAll("[^\\p{ASCII}-_ ]", "")
                .replace(' ', '_');
        List<String> possibleTimeZones =
                .filter(zid -> zid.endsWith("/" + tzCityName))
        System.out.format("%-12s %s%n", cityName, possibleTimeZones);

The output from this snippet is:

Abu Dhabi    []
Dubai        [Asia/Dubai]
Sydney       [Australia/Sydney]
Dhaka        [Asia/Dhaka]
Paris        [Europe/Paris]
Indianapolis [America/Indianapolis, America/Indiana/Indianapolis]
São Tomé     [Africa/Sao_Tome]

You will notice, though, that it didn’t find any time zone for Abu Dhabi because although the capital of the United Arab Emirates, it is not the largest city; Dubai is. You will notice too that two time zones were found for Indianapolis. The former is just an alias for the latter, though.

The city names used in the time zone database are the English names (when they exist) stripped of any accents. When a name is in two or three words, they are separated by underscores rather than spaces. So São Tomé becomes Sao_Tome. Therefore in the code I am performing this conversion. The way to strip off the accents was taken from another Stack Overflow answer, link below.