Using City names (example. Abu Dhabi, Sydney,Dhaka,Paris etc.) need to find local time zone. 2 digit country code can be used
-
1Hi, and welcome to Stack Overflow. Your question is a bit ambiguous, and doesn't show much in terms of effort on your part. Please read [How do I ask a good question?](https://stackoverflow.com/help/how-to-ask) and [idownvotedbecau.se/noattempt](https://idownvotedbecau.se/noattempt/). Also, questions in this area have been asked and answered many times before. You will get better results if you can show what you tried already, and be more specific about what did or did not work. Thanks. – Matt Johnson-Pint Apr 22 '19 at 21:32
1 Answers
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

- 81,772
- 15
- 137
- 161