【问题标题】:Detect if user's locale is set to 12-hour or 24-hour timeformat using javascript使用 javascript 检测用户的区域设置是否设置为 12 小时或 24 小时时间格式
【发布时间】:2020-06-29 15:11:27
【问题描述】:

如何检查用户是否使用 Javascript 使用 12 小时或 24 小时时间格式,是否使用 3rd 方库(如 moment.js) 我也尝试过new Date().toLocaleString(),但它在 Firefox 和 google chrome 中无法正常工作。 firefox 总是显示 12 小时格式,chrome 总是显示 24 小时格式

【问题讨论】:

    标签: javascript browser datetime-format time-format


    【解决方案1】:

    类似这样的:

    /*
     * Detects browser's locale 24h time preference
     * It works by checking whether hour output contains a space ('1 AM' or '01')
     */
    const isBrowserLocale24h = () =>
      !new Intl.DateTimeFormat([], { hour: 'numeric' }).format(0).match(/\s/);
    

    编辑:将第一个参数从 undefined 更改为 [],因为 MDN 文档说:To use the browser's default locale, pass an empty array

    检查Intl.DateTimeFormat的浏览器兼容性。

    您也许可以回退到以下内容,但我不确定 AM/PM 名称(无论使用哪个字符)是否位于所有语言环境的输出末尾。这只是检查最后一个字符是否为数字:

    Number.isFinite(Number((new Date()).toLocaleString().slice(-1)))
    

    【讨论】:

      【解决方案2】:

      Mario Bonaci 的回答对我来说并没有达到预期的效果,尽管它为我指明了正确的方向。这是我一开始尝试的:

      /*
       * Detects navigator locale 24h time preference
       * It works by checking whether hour output contains AM ('1 AM' or '01 h')
       */
      const isBrowserLocale24h = () =>
        !new Intl.DateTimeFormat(undefined, { hour: "numeric" })
          .format(0)
          .match(/AM/);
      

      它没有按预期工作,因为它显然采用了浏览器的安装语言,而不是用户首选语言。将 undefined 更改为 navigator.language 就可以了。在这里,我们根据用户的首选语言检查时间格式:

      /*
       * Detects navigator locale 24h time preference
       * It works by checking whether hour output contains AM ('1 AM' or '01 h')
       * based on the user's preferred language
       */
      const isBrowserLocale24h = () =>
        !new Intl.DateTimeFormat(navigator.language, { hour: "numeric" })
          .format(0)
          .match(/AM/);
      

      【讨论】:

      • 我很高兴这有帮助。您是否尝试像 MDN 文档所说的那样指定 [] 而不是 undefined?我改变了我的答案以反映这一点。感谢您的反馈!
      猜你喜欢
      • 2011-09-04
      • 1970-01-01
      • 1970-01-01
      • 2011-11-18
      • 2017-04-28
      • 1970-01-01
      • 1970-01-01
      • 2011-10-02
      • 2021-12-13
      相关资源
      最近更新 更多