使用 javascript 检测用户的区域设置是否设置为 12 小时或 24 小时时间格式

2023-12-21

如何使用 Javascript 检查用户是否使用 12 小时或 24 小时时间格式,无论是否使用第三方库(如 moment.js) 我也尝试过new Date().toLocaleString()但它没有在 Firefox 和 google chrome 中进行测试。 firefox 始终显示 12 小时格式,chrome 始终显示 24 小时时间格式


@Marko Bonaci 的回答很有帮助。我研究了他的评论“我不确定 AM/PM 名称(无论使用哪个字符)是否位于所有语言环境的输出末尾。”列出了 Google 搜索这个链接 https://spanishdict.com/answers/174077/when-keeping-time-how-do-you-translate-am-morning-and-pm-evening陈述用户的评论:

拉丁文缩写 a.m. 和 p.m. (通常写为“am”和“pm”、“AM”和“PM”或“A.M.”和“P.M.”) 用于英语、葡萄牙语(巴西)和西班牙语。 希腊语中的等价物是 π.μ。和μ.μ。分别。

这可以使用两个字母从浏览器的控制台进行验证ISO 639-1 https://en.wikipedia.org/wiki/List_of_ISO_639-1_codes代码“el”或三个字母的 ISO 639-2 代码“ell”:

new Intl.DateTimeFormat(["el"], { hour: "numeric" }).format();
// or
new Intl.DateTimeFormat("ell", { hour: "numeric" }).format();

这些行将返回带有本地化“AM”/“PM”字符串的值:

'7 π.μ.'
'7 μ.μ.'

我最终使用了他的建议,使用内置的 'Number https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Number' JavaScript 中的对象。

// UK english
Number.isInteger(Number(new Intl.DateTimeFormat("en-UK", { hour: "numeric" }).format()));
// Returns 'true'

// Greek
Number.isInteger(Number(new Intl.DateTimeFormat("el", { hour: "numeric" }).format()));
// Returns 'false'

// U.S.
Number.isInteger(Number(new Intl.DateTimeFormat("en-US", { hour: "numeric" }).format()));
// Returns 'false'

这是我的功能和评论:

const isBrowserLocaleClockType24h = (languages) => {
    // "In basic use without specifying a locale, DateTimeFormat
    // uses the default locale and default options."
    // Ref: developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/DateTimeFormat#using_datetimeformat
    // To be sure of the browser's language (set by the user
    // and may be different than the operating system's default language)
    // set the 'languages' parameter to 'navigator.language'.
    // E.g. isBrowserLocaleClockType24h(navigator.language);
    if (!languages) { languages = []; }

    // The value of 'hr' will be in the format '0', '1', ... up to '24'
    // for a 24-hour clock type (depending on a clock type of
    // 'h23' or 'h24'. See:
    // developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale
    // Intl.Locale.prototype.hourCycles
    // Returns an Array of hour cycle identifiers, indicating either
    // the 12-hour format ("h11", "h12") or
    // the 24-hour format ("h23", "h24").

    // A 12-hour clock type value has the format '7 AM', '10 PM', or
    // '7 π.μ.' (if the locale language is Greek as specified
    // by the two letter ISO 639-1 code "el" or 
    // three letter ISO 639-2 code "ell").

    const hr = new Intl.DateTimeFormat(languages, { hour: "numeric" }).format();

    // If there's no space in the value of the 'hr' variable then
    // the value is a string representing a number between and
    // can include '0' and '24'. See comment above regarding "hourCycles".
    // Return 'true' if a space exists.
    //if (!hr.match(/\s/)) { return true; }
    // Or simply:
    // return !hr.match(/\s/);

    // Alternatively, check if the value of 'hr' is an integer.
    // E.g. Number.isInteger(Number('10 AM')) returns 'false'
    // E.g. Number.isInteger(Number('7 π.μ.')) returns 'false'
    // E.g. Number.isInteger(Number('10')) returns 'true'
    return Number.isInteger(Number(hr));
};

Usage:

const isBrowserLocaleClock24h = isBrowserLocaleClockType24h();
// or
const isBrowserLocaleClock24h = isBrowserLocaleClockType24h(navigator.language);

使用 Intl.Locale().hourCycles

最后,对于较新的浏览器(截至 2022 年 12 月的 Firefox 除外),新的 Intl.Locale(navigator.language).hourCycles 列出在MDN https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/hourCycles.

// developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some#checking_whether_a_value_exists_in_an_array
const hourCycles = new Intl.Locale(navigator.language).hourCycles;
const isBrowserLocale24h = ["h23", "h24"].some(hourCycle => hourCycles.includes(hourCycle));

From https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Intl/Locale/hourCycle

Intl.Locale.prototype.hourCycle 属性是一个访问器属性,它返回区域设置使用的时间保持格式约定。

世界各地使用的计时惯例(时钟)有两种主要类型:12 小时制和 24 小时制。 hourCycle 属性使 JavaScript 程序员可以更轻松地访问特定区域设置使用的时钟类型。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

使用 javascript 检测用户的区域设置是否设置为 12 小时或 24 小时时间格式 的相关文章

随机推荐

  • Node.js:process.env 与全局有何不同?

    如何设置环境变量process env thing 42与创建全局变量不同global thing 42 什么时候更愿意process env thing over global 这两个对象的优点 缺点是什么 global是全局对象 pro
  • 颤动错误:类型“_Smi”不是类型“double”的子类型

    我使用 flutter 1 0 开发了一个应用程序 该应用程序在大多数 Android 和 iOS 手机上运行良好 但我发现有一部Android手机和一部iPhone无法打开该应用程序 只显示错误消息 类型 Smi 不是类型 double
  • 车把,加载外部模板文件

    我的目标是将所有 Handlebars 模板放在一个文件夹中 如下所示 templates products hbs templates comments hbs 我通过粗略的 Google 搜索在几个地方找到了这个片段 它显然会加载到外部
  • 忽略 Mercurial 中文件的未来更改,但仍然跟踪它[重复]

    这个问题在这里已经有答案了 可能的重复 Mercurial 如何忽略对跟踪文件的更改 https stackoverflow com questions 2856571 mercurial how to ignore changes to
  • IE 在打印时删除网页的颜色

    你好 我有一个网站 其背景颜色在打印时很重要 但 IE 会删除页面中的所有颜色 我知道有一些设置可以在 IE 上禁用此选项 但我不能依赖用户进入 IE 设置来禁用 IE 上的此选项 有什么方法可以从我的网页或其他方式禁用此功能吗 提前致谢
  • 在javascript中显示明天的名字?

    我试图在我们的电子商务网站上输出类似于以下内容的内容 Order by 5pm today for dispatch on Monday 显然 星期一 一词将被第二天的名称取代 最好是下一个工作日 即不是星期六或星期日 我有以下简单的 ja
  • Promise 函数延迟状态变量

    如何立即正确地存储 Promise 函数的值 我正在尝试使用 useEffect 挂钩 但我的状态仍然延迟 这是有问题的 因为如果用户正在验证他的购物车 则可能会应用错误的税 useEffect gt SalesTax getSalesTa
  • JavaScript。 Math.sqrt 将 NaN 赋予正数?

    我目前有一个脚本 可以从文本区域获取数字并用它们进行各种计算 我的标准差函数遇到问题 因为即使它的类型是数字 并且它是正数 56 它也不会输出该值 当我运行这段代码时 var variance findVariance array vari
  • Java 类中的 Grails @Autowire 不起作用

    我有一些 Java 代码 我想将它们转换为 Bean 可以通过依赖注入在 Grails 控制器和服务中使用 代码是基于这个here https spring io guides gs accessing data neo4j 作为独立的 J
  • 在 GridView 组件中显示多个图像时 Android 应用程序崩溃

    我对这个网站相当陌生 我来这里是因为我在其他地方找不到这个答案 所以我想看看是否可以获得一些帮助 我的项目中有一个 GridView 以及一个图像适配器 我需要以下代码的帮助 package com humanoid sigma impor
  • 在 Swift 中使用 @discardableResult 进行闭包

    斯威夫特 3 有介绍 https github com apple swift evolution blob master proposals 0047 nonvoid warn md the discardableResult函数的注释可
  • 如何在 SvelteKit 应用程序启动时执行代码

    我正在开发一个基于 SvelteKit 的应用程序 在服务器启动时 无论是在开发服务器启动 Node js 适配器启动时 我想执行一些诊断命令 此类操作的一个示例是对后端服务器执行 ping 操作 如果后端无法访问 则会提前失败 这主要是服
  • 如何获取已加载的 JNI 库的列表?

    正如主题所说 Java 中有没有一种方法可以获取在任何给定时间加载的所有 JNI 本机库的列表 免责声明 请注意 这个解决方案总是很hackish 现在在大多数情况下将不再起作用 查看本杰明的回答 https stackoverflow c
  • 使用 Java SDK、连接模式访问 Azure 服务总线

    有几个使用 C 配置服务总线环境以使用 http https 的示例 使用以下调用 ServiceBusEnvironment SystemConnectivity Mode ConnectivityMode Http 我的问题是 可以以及
  • 我如何设计一个数据库,用户可以在其中定义 M-D 关系中的详细表的字段和类型?

    我的应用程序有一个名为 events 的表 每个事件在 eventdata 表中都有大约 30 个标准字段 而且还有可以是任何名称或类型的用户定义字段 用户可以通过指定 x 个字段 文本 双精度 日期时间 布尔值 以及这些字段的名称来定义这
  • 无法在 Google Cloud SQL (MySQL) 上存储特殊字符

    我有两个 MySQL 实例 本地实例和 Google Cloud SQL 实例 使用字符集在两者上创建相同的数据库utf8mb4 当我运行时可以验证 show variables like character set database 同样
  • 将 lift-json 提取到具有上限的案例类中

    我花了最后一天的时间搜索和阅读各种网站和文章 试图自己找到这个问题的答案 但我没有找到任何有帮助的东西 我什至不确定这是否可行 我的问题是我正在尝试使用 lift json 解析和提取 Json 响应 响应由 4 部分组成 其中前 3 部分
  • 使用vba,是否可以从同一文件夹打开多个Excel工作簿并同时保持打开状态?

    这不是我第一次问这个问题 但我稍微改变了细节 希望能让它更清楚 这是我尝试过的代码的一个版本 Private Sub OpenWbsInPath zPath As String Dim zFile As String zPath IIf R
  • 从 celery 任务中调用 async_result.get()

    我有一个芹菜任务调用另一个任务remote任务 它在不同的芹菜应用程序上 在另一台服务器上 当我尝试从我的任务中 get 获取远程任务的结果时 如下所示 app task def my local task result from remo
  • 使用 javascript 检测用户的区域设置是否设置为 12 小时或 24 小时时间格式

    如何使用 Javascript 检查用户是否使用 12 小时或 24 小时时间格式 无论是否使用第三方库 如 moment js 我也尝试过new Date toLocaleString 但它没有在 Firefox 和 google chr