如何获取浏览器支持的完整长时区名称列表(如Europe/Berlin)
获取浏览器支持的所有时区名称数组的优化方案
我需要获取浏览器可识别的所有时区名称数组,用来提供给用户选择。
目前我知道可以通过以下方式获取用户当前所在时区的名称:
const browserLocale = new Intl.Locale(navigator.language); console.log(browserLocale.timeZones);
但我没找到能直接返回浏览器支持的全部时区名称列表的方法——这个列表会因浏览器及版本不同而有差异。
我自己写了一个效率极低的实现来获取全部名称:
function collectAllPossibleTimeZoneNames() { const az = Array.from({ length: 26 }, (_, i) => String.fromCharCode(97 + i)); const aazz = az.flatMap((a) => az.map((b) => a + b)); const AAZZ = aazz.map((item) => item.toUpperCase()); const aazzAAZZ = aazz.flatMap((a) => AAZZ.map((b) => `${a}-${b}`)); const length = aazzAAZZ.length; let oldProgress = ""; const timeZoneNames = aazzAAZZ.reduce( (set, currentLocale, index) => { const progress = ((index / length) * 100).toFixed(1); if (progress !== oldProgress) { oldProgress = progress; console.log(`${progress}%`); } const locale = new Intl.Locale(currentLocale); if (!locale || !locale.timeZones || locale.timeZones.length === 0) { return set; } locale.timeZones.forEach((timeZoneName) => set.add(timeZoneName)); return set; }, new Set(), ); const timeZoneNamesArray = Array.from(timeZoneNames); timeZoneNamesArray.sort(); return timeZoneNamesArray; } console.log(collectAllPossibleTimeZoneNames());
这个方案几乎没用,因为耗时太长(在我的系统上大概需要2分钟)。我可以运行一次把结果存入数据库,但不同用户的浏览器支持的时区名称可能不一样。
请问有没有更好的解决方案?
内容的提问来源于stack exchange,提问作者AFE-GmdG
相关产品推荐
相关产品推荐

