You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何获取用户当前区域设置的首选hourCycle?调用返回undefined问题排查

正确获取浏览器区域设置的首选hourCycle属性

你之前的代码返回undefined,是因为直接指定en-US创建Intl.Locale实例时,不会自动关联用户的实际区域偏好,且部分基础区域标识默认不包含hourCycle属性。以下是两种可靠的获取方式:

方法一:通过Intl.DateTimeFormat解析

利用Intl.DateTimeFormat自动适配用户当前区域设置的特性,通过resolvedOptions()提取hourCycle:

const dtf = new Intl.DateTimeFormat();
const resolvedOpts = dtf.resolvedOptions();
console.log(resolvedOpts.hourCycle); // 输出用户区域的首选hourCycle,比如"h12"或"h24"

方法二:通过Intl.Locale结合用户区域标识

先获取用户当前的语言标识,再通过maximize()扩展Locale实例以获取完整属性:

const userLocale = navigator.language;
const locale = new Intl.Locale(userLocale);
// maximize()会补全区域的默认扩展属性
const fullLocale = locale.maximize();
console.log(fullLocale.hourCycle);

说明

  • 方法一的兼容性和可靠性更高,因为resolvedOptions()直接返回浏览器实际使用的区域配置。
  • 方法二中,部分基础区域标识默认不携带hourCycle,需要调用maximize()来获取完整的默认属性集。

内容的提问来源于stack exchange,提问作者tyteen4a03

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.17 14:58:15