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 = zids.stream()
                .filter(zid -> zid.endsWith("/" + tzCityName))
                .collect(Collectors.toList());
        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.

Links

  • List of tz database time zones on Wikipedia
  • Answer by Erick Robertson to Is there a way to get rid of accents and convert a whole string to regular letters?
Answer from Anonymous on Stack Overflow
Top answer
1 of 1
5

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 = zids.stream()
                .filter(zid -> zid.endsWith("/" + tzCityName))
                .collect(Collectors.toList());
        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.

Links

  • List of tz database time zones on Wikipedia
  • Answer by Erick Robertson to Is there a way to get rid of accents and convert a whole string to regular letters?
🌐
Coderanch
coderanch.com › t › 583127 › java › Timezone-City-State-Province-Country
To know Timezone given City,State/Province,Country (Java in General forum at Coderanch)
Hi all, I am trying to look for ... input if you have any experience on it. StackOverflow Post Thanks Maulin ... Hi Maulin, If you look at the getTimeZone() method of the Calendar class clearly you can see there is a way to get a TimeZone from a given Calendar....
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › util › TimeZone.html
TimeZone (Java Platform SE 8 )
1 week ago - In Honolulu, for example, its raw offset changed from GMT-10:30 to GMT-10:00 in 1947, and this method always returns -36000000 milliseconds (i.e., -10 hours). ... Gets the ID of this time zone. ... Sets the time zone ID. This does not change any other data in the time zone object. ... ID - the new time zone ID. ... Returns a long standard time name of this TimeZone suitable for presentation to the user in the default locale.
🌐
Jenkov
jenkov.com › tutorials › java-date-time › java-util-timezone.html
Java's java.util.TimeZone
June 23, 2014 - TimeZone timeZone1 = TimeZone.getTimeZone("America/Los_Angeles"); TimeZone timeZone2 = TimeZone.getTimeZone("Europe/Copenhagen"); Calendar calendar = new GregorianCalendar(); long timeCPH = calendar.getTimeInMillis(); System.out.println("timeCPH = " + timeCPH); System.out.println("hour = " + calendar.get(Calendar.HOUR_OF_DAY)); calendar.setTimeZone(timeZone1); long timeLA = calendar.getTimeInMillis(); System.out.println("timeLA = " + timeLA); System.out.println("hour = " + calendar.get(Calendar.HOUR_OF_DAY)); ... Notice how the time in milliseconds is the same with both time zones, but that the hour of day has changed from 20 to 11.
🌐
Stack Overflow
stackoverflow.com › questions › 58396750
Need timezone based on the ISO country code and city in Java - Stack Overflow
@Tim, I think he means that one city name, like, say "Manchester", can be in more than one country, not talking about a single physical city split between two countries! ... Rough way I found to achieve is - private static String getSourceLocalTimeZone(String countryCode, String city, String sourceLocalTimeZone) { String[] timeZones = com.ibm.icu.util.TimeZone.getAvailableIDs(countryCode); for (String timeZone : timeZones) { String cityFromTimeZone = null; String[] value = timeZone.split("/"); if (value != null && value.length > 0) { cityFromTimeZone = value[value.length - 1].replace("_", " ")
🌐
Oracle
docs.oracle.com › javase › 7 › docs › api › java › util › TimeZone.html
TimeZone (Java Platform SE 7 )
In Honolulu, for example, its raw offset changed from GMT-10:30 to GMT-10:00 in 1947, and this method always returns -36000000 milliseconds (i.e., -10 hours). ... Gets the ID of this time zone. ... Sets the time zone ID. This does not change any other data in the time zone object. ... ID - the new time zone ID. ... Returns a long standard time name of this TimeZone suitable for presentation to the user in the default locale.
🌐
Dariawan
dariawan.com › tutorials › java › java-timezone-examples
Java TimeZone Examples | Dariawan
August 17, 2019 - Calendar's Date/Time: 09/04/1980 ... ID : Asia/Jakarta Time Zone Name : West Indonesia Time · We can use Calendar's setTimeZone() to convert between TimeZone ... import java.util.Calendar; import java.util.TimeZone; public class ...
Find elsewhere
🌐
Coderanch
coderanch.com › t › 500864 › java › time-zone-city-state-country
get time zone when city, state and country are input (Java in General forum at Coderanch)
June 28, 2010 - Hi, Is there a method in JAVA to get time zone when city, state and country are input? Thanks, Steve ... Java API has a Timezone class: http://java.sun.com/j2se/1.4.2/docs/api/java/util/TimeZone.html Good Luck
🌐
Lunatech
blog.lunatech.com › posts › 2008-12-20-getting-list-time-zones-java-and-seam
Getting a list of time zones in Java and Seam
December 20, 2008 - final List<TimeZone> timeZones = new ArrayList<TimeZone>(); for (final String id : timeZoneIds) { timeZones.add(TimeZone.getTimeZone(id)); } However, there are a few small details to take care of. First, the list contains a lot of duplication since there is more than one kind of ID for the same time zone: city names, like Europe/Amsterdam · three-letter codes, including unfamiliar ones like WET (Western European Time) a handful of country names, like Egypt · GMT offsets, like Etc/GMT+2 · other random entries, like SystemV/EST5. Taking a cue from existing user-interfaces, like the OS X time zone selector, we shall filter the list to the first format - continent and city - using a regular expression: ^(Africa|America|Asia|Atlantic|Australia|Europe|Indian|Pacific)/.* Second, TimeZone.getAvailableIDs() returns an unsorted list, so we will sort the result by ID.
🌐
Quora
quora.com › How-do-I-get-the-date-and-time-of-a-specific-time-zone-in-Java
How to get the date and time of a specific time zone in Java - Quora
Answer (1 of 2): Since Java 1.8 it is possible to use the Date-Time API in [code ]java.time[/code] package. 1.It is possible to specify the timezone by the ZoneId. * Time zone by region based id of ZoneId e.g.: [code ]ZoneId zoneId = ZoneId.of("America/Los_Angeles");[/code] Regions and zone ru...
🌐
GeeksforGeeks
geeksforgeeks.org › java › java-util-timezone-class-set-1
Java.util.TimeZone Class | Set 1 - GeeksforGeeks
December 3, 2021 - TimeZone timezone = TimeZone.getDefault(); // Get the Name of Time Zone String LocalTimeZoneDisplayName = timezone.getDisplayName(); // Print the Name of Time Zone System.out.println(LocalTimeZoneDisplayName); } } ... Syntax :public static TimeZone ...
Top answer
1 of 1
1

java.time can give you an approximation

    ZoneId inputZone = ZoneId.of("Europe/Warsaw");
    
    ZoneRules rules = inputZone.getRules();
    Instant timeNow = Instant.now();
    ZoneOffset currentOffset = rules.getOffset(timeNow);
    ZoneOffsetTransition lastTransition = rules.previousTransition(timeNow);
    ZoneOffsetTransition nextTransition = rules.nextTransition(timeNow);
    for (String zid : ZoneId.getAvailableZoneIds()) {
        ZoneRules zidRules = ZoneId.of(zid).getRules();
        if (zidRules.getOffset(timeNow).equals(currentOffset)
                && Objects.equals(zidRules.previousTransition(timeNow), lastTransition)
                && Objects.equals(zidRules.nextTransition(timeNow), nextTransition)) {
            System.out.println(zid);
        }
    }

Output from this snippet is:

Europe/Brussels
Europe/Warsaw
CET
Europe/Luxembourg
Europe/Malta
Europe/Busingen
Europe/Skopje
Europe/Sarajevo
Europe/Rome
Europe/Zurich
Europe/Gibraltar
Europe/Vaduz
Europe/Ljubljana
Europe/Berlin
Europe/Stockholm
Europe/Budapest
Europe/Zagreb
Europe/Paris
Africa/Ceuta
Europe/Prague
Europe/Copenhagen
Europe/Vienna
Europe/Tirane
MET
Europe/Amsterdam
Europe/San_Marino
Poland
Europe/Andorra
Europe/Oslo
Europe/Podgorica
Atlantic/Jan_Mayen
Europe/Madrid
Europe/Belgrade
Europe/Bratislava
Arctic/Longyearbyen
Europe/Vatican
Europe/Monaco

Note that some of the zone IDs in the output are deprecated and/or aliases for other IDs in the output.

I am assuming that if a time zone has all of the following three, then it’s similar enough to be output.

  1. The same current UTC offset (in this case +01:00)
  2. The same last transition (in this case from +02:00 to +01:00 at 2020-10-25T03:00+02:00)
  3. The same next transition (in this case to +02:00 at 2021-03-28T02:00+01:00)

Java doesn’t know the country of each time zone. You may look them up in the second link below.

They are still different time zones

There are reasons why different time zone IDs are used. One of the most common reasons is that they in fact identify time zones that don’t always have the same time. To take the two time zones from your question as an example, Europe/Berlin and Europe/Warsaw, a few of the differences are:

  • Warsaw introduced summer time (DST) from 1977. Berlin did not until 1980.
  • Before World War I, Berlin was at offset +01:00 while Warsaw was as +01:24.
  • Up to 1893 Berlin was at offset +00:53:28 all year, more than half an hour behind Warsaw.
  • No one knows what the future will bring for each of those two time zones.

Links

  • Oracle tutorial: Date Time explaining how to use java.time.
  • List of tz database time zones
  • Time Changes in Berlin Over the Years
  • Time Changes in Warsaw Over the Years
🌐
Codereye
codereye.com › 2009 › 05 › getting-time-zone-list-in-java.html
Getting Time Zone list in Java - Coder Eye
Like Locale function: Locale.getISOCountries() and Locale.getISOLanguages(), TimeZone class also has a method for getting all time zone IDs: TimeZone.getAvailableIDs(). But, unlike countries and languages list, the time zone list contains many duplicate time zones, as well as undesired time zones like GMT+6 or country time zones like: Poland. We would like to build neat time zones list, that contains only continent and city time zones.
🌐
ProcessWire
processwire.com › off topic › dev talk
Get timezone for a city? - Dev Talk - ProcessWire Support Forums
February 25, 2021 - Does anyone know of a website/tool that will let me type in the name of a city, or maybe click on a map, and get the PHP-compatible timezone name for that location? So for example if I typed or clicked on the location Christchurch, New Zealand I would get "Pacific/Auckland". It doesn't need to be...
🌐
Oracle
docs.oracle.com › javase › 8 › docs › api › java › time › ZoneId.html
ZoneId (Java Platform SE 8 )
1 week ago - The detailed format of the region ID depends on the group supplying the data. The default set of data is supplied by the IANA Time Zone Database (TZDB). This has region IDs of the form '{area}/{city}', such as 'Europe/Paris' or 'America/New_York'. This is compatible with most IDs from TimeZone.
🌐
GitHub
github.com › RomanIakovlev › timeshape
GitHub - RomanIakovlev/timeshape: Java library to find timezone based on geo coordinates · GitHub
Java library to find timezone based on geo coordinates - RomanIakovlev/timeshape
Starred by 195 users
Forked by 41 users
Languages   Java 90.3% | Makefile 9.7%