使用javascript检测用户的语言环境是否设置为12小时制或24小时制 [英] Detect if user's locale is set to 12-hour or 24-hour timeformat using javascript

查看:78
本文介绍了使用javascript检测用户的语言环境是否设置为12小时制或24小时制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何使用Java脚本检查用户使用的是12hr还是24hr时间格式,以及是否使用了诸如moment.js之类的第三方库我也尝试过 new Date().toLocaleString(),但是在Firefox和谷歌浏览器中无法通过测试.firefox始终显示12hr格式,chrome始终显示24hrs时间格式

how to check whether the user is using 12hr or 24hr time format using Javascript with or without using 3rd party library like moment.js I also tried new Date().toLocaleString() but it is not working tested in firefox and google chrome. firefox always shows 12hr format and chrome always shows 24hrs time format

推荐答案

马里奥·博纳奇(Mario Bonaci)的回答虽然为我指出了正确的方向,却没有达到我的预期.这是我最初尝试的内容:

Mario Bonaci's answer didn't work as expected for me though it pointed me to the right direction. Here's what I tried at first:

/*
 * 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 达到了目的.在这里,我们正在根据用户偏好的语言检查时间格式:

It didn't work as expected as it apparently takes the browser's install language and not the user preferred language. Changing the undefined to navigator.language did the trick. Here, we're checking the time format based on the user's preferred 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/);

这篇关于使用javascript检测用户的语言环境是否设置为12小时制或24小时制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆