简体   繁体   English

如果用户的机器使用 12 小时制(上午/下午)或 24 小时制(军用时间),则使用 javascript 检测

[英]Detect with javascript if user's machine is using 12 hour clock (am/pm) or 24 clock (military time)

Is it possible to detect if user's machine is using 12 hour clock (am/pm) or 24 hour clock (military time)?是否可以检测用户的机器是使用 12 小时制(上午/下午)还是 24 小时制(军用时间)?

One way would be to check users locales, but then it is just massive list of locale comparison and someone from US who wants 12 hour clock can send me just en locale, not US_en and I have no way of knowing her preferences.一种方法是检查用户语言环境,但它只是大量的语言环境比较列表,来自美国的想要 12 小时制的人可以只向我发送语言环境,而不是 US_en,我无法知道她的偏好。 At the same time someone from US might be set her machine to use 12 hour time format and doesn't want 12 hour clock.同时,来自美国的某个人可能将她的机器设置为使用 12 小时制时间格式,而不想要 12 小时制。

EDIT:编辑:

date.toLocaleTimeString();

Would work it theory, as user Mouser suggested below, but unfortunately it's bugged on WebKit browsers (tested on Chrome and new Opera on Windows) and for some reason always returns am/pm time.正如用户 Mouser 在下面建议的那样,理论上会起作用,但不幸的是,它在 WebKit 浏览上被窃听(在 Windows 上的 Chrome 和新 Opera 上测试)并且由于某种原因总是返回上午/下午时间。

Example: http://jsfiddle.net/sjuaL3p4/示例: http : //jsfiddle.net/sjuaL3p4/

So I guess I have to rephrase my question if anyone has an idea how to accomplish it on webkit browsers also.所以我想我必须重新表述我的问题,如果有人知道如何在 webkit 浏览器上完成它。

You can utilize the Internationalization API with resolvedOptions to determine the hourCycle :您可以利用与国际化API resolvedOptions确定hourCycle

const locale = navigator.language
Intl.DateTimeFormat(locale,  { hour: 'numeric' }).resolvedOptions().hourCycle // ?
Intl.DateTimeFormat('en-US', { hour: 'numeric' }).resolvedOptions().hourCycle // h12
Intl.DateTimeFormat('en-GB', { hour: 'numeric' }).resolvedOptions().hourCycle // h23

This solution works in most browsers, but bugs in Chrome.此解决方案适用于大多数浏览器,但在 Chrome 中存在错误。

 var date = new Date(Date.UTC(2012, 11, 12, 3, 0, 0)); var dateString = date.toLocaleTimeString(); //apparently toLocaleTimeString() has a bug in Chrome. toString() however returns 12/24 hour formats. If one of two contains AM/PM execute 12 hour coding. if (dateString.match(/am|pm/i) || date.toString().match(/am|pm/i) ) { //12 hour clock console.log("12 hour"); } else { //24 hour clock console.log("24 hour"); }

Workaround Chrome;解决方法 Chrome; A proof of concept概念证明

This is an ugly work-around for Chrome.这是 Chrome 的一个丑陋的解决方法。 It sniffs out the users country_code via reverse geolocation .它通过reverse geolocation嗅探用户country_code That code is checked against an array with countries using the 12 hour system.该代码根据使用 12 小时制的国家/地区数组进行检查。 This solution is ugly because you need user permission to get geolocation data and if the users locale is different it will give the wrong information, but will provide you with the country of the user.这个解决方案很难看,因为您需要用户许可才能获取地理位置数据,如果用户区域设置不同,它会提供错误的信息,但会为您提供用户所在的国家/地区。 I strongly advise against using this example .我强烈建议不要使用这个例子 It's purely for inspiration purposes.这纯粹是为了灵感。 I made it up as a proof of concept.我把它作为概念证明。

 function getClockChrome() { navigator.geolocation.getCurrentPosition(function(pos) { var url = "http://nominatim.openstreetmap.org/reverse?format=json&lat="+pos.coords.latitude+"&lon="+pos.coords.longitude+"&addressdetails=1&accept-language=en_US&json_callback=chromeClockCallBack"; var script = document.createElement('script'); script.src = url; document.body.appendChild(script); }, function() { //no access to location }, { enableHighAccuracy: true, timeout: 5000, maximumAge: 0 } ); } getClockChrome(); var dateCountryCode = ['US', 'GB', 'PH', 'CA', 'AU', 'NZ', 'IN', 'EG', 'SA', 'CO', 'PK', 'MY']; function chromeClockCallBack(data) { //Request succeeded if (dateCountryCode.indexOf(data.address.country_code.toUpperCase()) > -1) { alert("12 hour clock"); } else { alert("24 hour clock"); } }

This works for all locales including ones with non-Latin number systems.这适用于所有语言环境,包括非拉丁数字系统的语言环境。 Because it is that flexible, you need to know if and how you will handle that type of scenario.因为它非常灵活,所以您需要知道是否以及如何处理这种类型的场景。

This does not support IE 10 or earlier.这不支持 IE 10 或更早版本。

 function is12Hour(locale) { return !!new Intl.DateTimeFormat(locale, { hour: 'numeric' }).format(0).match(/\\s/); } console.log(is12Hour()); console.log(is12Hour('en-GB')); console.log(is12Hour('ar-SA'));

toLocaleTimeString should give the time in a format that reflects the user's preferences but it is unreliable. toLocaleTimeString应该以反映用户偏好的格式给出时间,但它不可靠。

I'm on a Debian system.我在 Debian 系统上。 The output of locale is: locale的输出是:

LANG=en_US.utf8
LANGUAGE=
LC_CTYPE="en_US.utf8"
LC_NUMERIC="en_US.utf8"
LC_TIME="en_US.utf8"
LC_COLLATE="en_US.utf8"
LC_MONETARY="en_US.utf8"
LC_MESSAGES="en_US.utf8"
LC_PAPER="en_US.utf8"
LC_NAME="en_US.utf8"
LC_ADDRESS="en_US.utf8"
LC_TELEPHONE="en_US.utf8"
LC_MEASUREMENT="en_US.utf8"
LC_IDENTIFICATION="en_US.utf8"
LC_ALL=

Here are a few experiments with date :以下是一些关于date实验:

$ date +%X
05:23:32 PM
$ LANG=en_GB date +%X
17:24:06
$ LC_TIME=en_GB date +%X
17:24:22

The %X format tells date to output the time according to the locale. %X格式告诉date根据语言环境输出时间。 The results above are exactly as expected.上面的结果完全符合预期。 Setting LC_TIME is a way to change only the time format but keep everything else in the locale intact.设置LC_TIME是一种仅更改时间格式但保持区域设置中的所有其他内容不变的方法。 So someone in the US could use a 24h time format even if the default for en_US is 12.因此,即使en_US的默认值为 12,美国的某些人也可以使用 24 小时时间格式。

I've tried Mouser's script on my system:我已经在我的系统上尝试过Mouser 的脚本

$ firefox --no-remote
[Shows a time in the 12 hour format, as expected.]
$ LANG=en_GB firefox --no-remote
[Shows a time in the 24 hour format, as expected.]

So far so good.到现在为止还挺好。 However,然而,

$ LC_TIME=en_GB firefox --no-remote
[Shows a time in the 12 hour format, this is wrong!]

I get the same results with Chrome.我用 Chrome 得到了相同的结果。 It seems that both Firefox and Chrome ignore LC_TIME . Firefox 和 Chrome 似乎都忽略了LC_TIME

Besides the fact that this should never be done , .toLocaleTimeString() wouldn't be a good solution even if it did work across browsers.除了永远不应该这样做的事实之外, .toLocaleTimeString()也不是一个好的解决方案,即使它确实可以跨浏览器工作。 It returns a time string following the format set by the user's computer, but it's possible to have a 24-hour clock that still shows AM/PM, as well as a 12-hour clock that doesn't.它按照用户计算机设置的格式返回一个时间字符串,但可能有 24 小时制仍显示 AM/PM,以及 12 小时制不显示。 It's not feasible to accurately or reliably detect this.准确或可靠地检测到这一点是不可行的。

This simple line seems to be working for me.这条简单的线似乎对我有用。

var is24 = ((new Date(2014, 01, 01, 15, 0, 0, 0)).toLocaleTimeString().indexOf("15") > -1);

Though it still doesn't work in Chrome (works in IE and Firefox)虽然它仍然无法在 Chrome 中工作(在 IE 和 Firefox 中工作)

This works for me in Chrome.这在 Chrome 中对我有用。 I used the selected answer from @Mouser which was not working in Chrome.我使用了从 @Mouser 选择的答案,它在 Chrome 中不起作用。

    let result = false;
    const date = new Date();
    const dateString = date.toLocaleTimeString(language, {
        timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
        timeStyle: 'short'
    });
    
    if (dateString.match(/am|pm/i) || date.toString().match(/am|pm/i)) {
        result = true;
    }
    else {
        result = false;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 12 小时 Javascript 时钟显示 24 时间,错误的 AM/PM - 12 hour Javascript Clock Showing 24 time, Wrong AM/PM 将 24 小时制转换为 12 小时制并跟踪 AM/PM - Converting a 24 hour clock to a 12 hour clock and keeping track of AM/PM 最后使用Javascript修改的页面,其12小时制显示am或pm - Page last modified using Javascript with 12 hour clock showing am or pm 使用 Javascript 将 24 小时制转换为 12 小时制 - Converting 24 hour time to 12 hour time w/ AM & PM using Javascript Javascript -- 检测用户的区域设置是否设置为使用 12 小时或 24 小时时间格式 - Javascript -- Detect if user's locale are set to use 12-hour or 24-hour time format 时间轴24小时制 - Time axis in 24 hour clock Javascript:将 24 小时时间字符串转换为带有 AM/PM 且无时区的 12 小时时间 - Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone 使用 javascript 检测用户的区域设置是否设置为 12 小时或 24 小时时间格式 - Detect if user's locale is set to 12-hour or 24-hour timeformat using javascript 24小时制javascript正则表达式 - 24 hour clock regex for javascript 12 小时制不显示,但 24 小时制显示正常 - 12 hour clock not displaying, but 24 hour clock displaying fine
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM