问题描述
使用城市名称(例如阿布扎比、悉尼、达卡、巴黎等)需要查找本地时区.可以使用 2 位国家代码
Using City names (example. Abu Dhabi, Sydney,Dhaka,Paris etc.) need to find local time zone. 2 digit country code can be used
推荐答案
对于涵盖所有可能的城市名称的解决方案,这将需要一个包含城市及其相应时区的数据库.由于存在同名城市,情况会变得更加复杂,因此您可能会产生不明确的输入.例如,通过巴黎,我想您打算将法国的首都和最大城市称为欧洲,但在其他地方也存在称为巴黎的城镇.不知道有没有合适的数据库,可以搜索一下.
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.
不过,我可以让您了解 Java 中内置的内容.时区的 ID 格式为 region/city,例如 Australia/Sydney
和 Asia/Dubai
.用于命名时区的城市是该时区中人口最多的地区,因此即使一个国家或州只有一个时区,城市也不一定是首都.但如果城市重合,我们可以找到区域.
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);
}
这个片段的输出是:
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.
时区数据库中使用的城市名称是去除了任何重音符号的英文名称(如果存在).当名称由两个或三个单词组成时,它们之间用下划线而不是空格分隔.所以圣多美变成了圣多美.因此在代码中我正在执行此转换.去除重音的方法取自另一个 Stack Overflow 答案,链接如下.
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.
这篇关于在 Java 中使用城市名称获取本地时区的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!