简体   繁体   English

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

[英]Javascript -- Detect if user's locale are set to use 12-hour or 24-hour time format

One way to do that is to parse new Date().toLocaleString() .一种方法是解析new Date().toLocaleString() But this doesn't work in chromium/webkit since the string it returns isn't dependent of the user's locale (see bug report at http://code.google.com/p/chromium/issues/detail?id=3607 )但这在 chromium/webkit 中不起作用,因为它返回的字符串不依赖于用户的语言环境(参见http://code.google.com/p/chromium/issues/detail?id=3607的错误报告)

I emphasize that I'm looking for a solution that is client side only and that works in chromium.我强调我正在寻找一种仅适用于客户端并且适用于铬的解决方案。

It's been a few years since this was last answered and a few technologies have been introduced to solve the issue.自从上次回答这个问题以来已经有几年了,并且已经引入了一些技术来解决这个问题。 One such technology is Intl.DateTimeFormat , which provides a wealth of information about date formats for various locales.一种这样的技术是Intl.DateTimeFormat ,它提供了有关各种语言环境的日期格式的大量信息。

 console.log(new Intl.DateTimeFormat().resolvedOptions()); console.log(new Intl.DateTimeFormat().resolvedOptions().hour12);
 .as-console-wrapper { max-height: 100%;important; }

However, most locales don't define a default for the hour12 option.但是,大多数语言环境都没有为hour12选项定义默认值。 So, if this returns undefined , I'd look at the formatToParts function.所以,如果返回undefined ,我会查看formatToParts function。

 const hourParts = new Intl.DateTimeFormat(undefined, { hour: 'numeric' }).formatToParts(new Date(2020, 0, 1, 13)); console.log(hourParts);
 .as-console-wrapper { max-height: 100%;important; }

The output from that should look like (for your browser's current language; in my case, "en-US"): output 应该看起来像(对于您浏览器的当前语言;在我的情况下,“en-US”):

[
  {
    "type": "hour",
    "value": "1"
  },
  {
    "type": "literal",
    "value": " "
  },
  {
    "type": "dayPeriod",
    "value": "PM"
  }
]

Getting the length of the value of the part with type equal to "hour" will tell you whether it was formatted with twelve or twenty-four hour time.获取type等于"hour"的部分value的长度将告诉您它是用 12 小时还是 24 小时时间格式化的。

For instance, I happen to know that in Japan, they use twenty four hour time, so I can check that:例如,我碰巧知道在日本,他们使用二十四小时的时间,所以我可以检查一下:

 const hourParts = new Intl.DateTimeFormat('ja-JP', { hour: 'numeric' }).formatToParts(new Date(2020, 0, 1, 13)); console.log(hourParts.find(part => part.type === 'hour').value.length);
 .as-console-wrapper { max-height: 100%;important; }

And I know the the US defaults to twelve hour time:而且我知道美国默认为十二小时时间:

 const hourParts = new Intl.DateTimeFormat('en-US', { hour: 'numeric' }).formatToParts(new Date(2020, 0, 1, 13)); console.log(hourParts.find(part => part.type === 'hour').value.length);
 .as-console-wrapper { max-height: 100%;important; }

It would be easy enough to wrap this in a function:将其包装在 function 中会很容易:

 function localeUses24HourTime(langCode) { return new Intl.DateTimeFormat(langCode, { hour: 'numeric' }).formatToParts(new Date(2020, 0, 1, 13)).find(part => part.type === 'hour').value.length === 2; } console.log(localeUses24HourTime()); // undefined means current user's language console.log(localeUses24HourTime('en-US')); // a specific language known to be false console.log(localeUses24HourTime('ja-JP')); // a specific language known to be true
 .as-console-wrapper { max-height: 100%;important; }

You may find this more or less complicated than parsing the output of toLocaleString() .您可能会发现这比解析toLocaleString()的 output 或多或少复杂。

Note: I switched from using the term "locale" to "language" midway through my answer.注意:我在回答中途从使用术语“语言环境”切换到“语言”。 This is due to how the specification is written and how information is specified.这是由于规范的编写方式和信息的指定方式。 en-US and ja-JP are BCP language codes, passed to the constructor of Intl.DateTimeFormat to look up date and time formatting rules. en-USja-JP是 BCP 语言代码,传递给Intl.DateTimeFormat的构造函数以查找日期和时间格式规则。 The specification uses the term locale to refer to this piece of information but indeed it is a language identifier, which, while it may contain a region (the US and JP in the mentioned codes), does not require them, nor does that region necessarily indicate the user's locale (consider a person who speaks Spanish and learned it in Spain [and therefore would use the language code 'es-ES'], but lives in the United States, where the dates are formatted differently than in Spain).规范使用术语locale来指代这条信息,但实际上它是一种语言标识符,虽然它可能包含一个区域(提到的代码中的USJP ),但不需要它们,该区域也不一定指示用户的区域设置(考虑一个说西班牙语并在西班牙学习的人[因此将使用语言代码'es-ES'],但居住在美国,日期格式与西班牙不同)。

As long as Chromium doesn't fix toLocaleString() there is no way to do that in chromium.只要 Chromium 不修复toLocaleString()就没有办法在 chromium 中做到这一点。

For Firefox and IE parsing toLocaleString() will give that information.对于 Firefox 和 IE 解析toLocaleString()将提供该信息。

EDIT编辑
Apparently toLocalString() is now fixed in Chrome.显然toLocalString()现在已在 Chrome 中修复。 The parsing of toLocaleString() is therefore a solution.因此toLocaleString()的解析是一种解决方案。

You should never search for local pattern this way.您永远不应该以这种方式搜索本地模式。 toLocaleString() is clearly a mistake (derived from Java) and should not be used. toLocaleString()显然是一个错误(源自 Java),不应使用。 As you mentioned, this method is not well supported in various browsers (Chrome is just one of them).正如您所提到的,这种方法在各种浏览器中都没有得到很好的支持(Chrome 只是其中之一)。
In fact the only web browser (from popular ones) which get it about right (but not 100% right) is IE.事实上,唯一正确(但不是 100% 正确)的 web 浏览器(来自流行浏览器)是 IE。

To correctly format date depending on Locale, please use Globalize .要根据区域设置正确格式化日期,请使用Globalize It contains localized patterns dumped out of.Net.它包含从 .Net 中导出的本地化模式。
You may alternatively want to use Dojo which also allows Locale-aware formatting, but based on CLDR .您也可以选择使用Dojo ,它也允许区域设置感知格式,但基于CLDR

Edit, new facts exist编辑,新的事实存在

There is a new standard for I18n in JavaScript - ECMA-402 .在 JavaScript - ECMA-402中有一个新的 I18n 标准。 This standard in fact allows for using JS Date 's object.该标准实际上允许使用 JS Date的 object。 However, one should always pass a language tag:但是,应该始终传递一个语言标签:

var date = new Date();
var formatted = date.toLocaleString('de-DE');

The only problem with this is, the only web browser I am aware of that currently implements ECMA-402 is Google Chrome.唯一的问题是,我知道目前实现 ECMA-402 的唯一 web 浏览器是 Google Chrome。

For now it seems that still the way to go is to use something along the lines of iLib .目前看来,通往go的方法仍然是使用类似 iLib 的东西。

Parse (new Date).toLocaleString() for all browsers except Chrome, and check navigator.language against a map of locales and their time formats for Chrome.为除 Chrome 之外的所有浏览器解析(new Date).toLocaleString() ,并针对 Chrome 的区域设置及其时间格式的 map 检查navigator.language

I know it would be the least favoured way of doing it, but could you not just check the time?我知道这将是最不受欢迎的方式,但你能不能只检查一下时间?

If the time is before 12, set the time to 1pm and test if the output is 13 or 1.如果时间在 12 点之前,将时间设置为下午 1 点,并测试 output 是 13 还是 1。

I know its a shoehorn of an idea, but if placed into a nice Date.prototype.is24hour(), returns true;我知道这是一个想法,但如果放入一个不错的 Date.prototype.is24hour() 中,则返回 true; It could work nicely?它可以很好地工作吗?

I use http://www.datejs.com/ with dates.我使用带有日期的http://www.datejs.com/ tends to do everything I need, So you could use that alongside a custom prototype function, and that would give you what you need!倾向于做我需要的一切,因此您可以将其与自定义原型功能一起使用,这将为您提供所需的东西!

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

相关问题 使用 javascript 检测用户的区域设置是否设置为 12 小时或 24 小时时间格式 - Detect if user's locale is set to 12-hour or 24-hour timeformat using javascript JavaScript 确定浏览器是否使用 12 小时或 24 小时格式显示时间输入 - JavaScript to determine if browser is displaying the time input using a 12-hour or 24-hour format 显示 12 小时制和 24 小时制时间 - Display 12-hour and 24-hour time Javascript:将 24 小时时间字符串转换为带有 AM/PM 且无时区的 12 小时时间 - Javascript: convert 24-hour time-of-day string to 12-hour time with AM/PM and no timezone Moment.js接受12小时和24小时时间 - Moment.js Accept both 12-hour and 24-hour time JavaScript以12小时格式随机生成时间 - JavaScript random generate time in 12-hour format 根据 toLocaleTimeString() 将 12 小时 hh:mm AM/PM 转换为 24 小时 hh:mm - convert 12-hour hh:mm AM/PM to 24-hour hh:mm depending on toLocaleTimeString() 将 12 小时制 hh:mm AM/PM 转换为 24 小时制 hh:mm - convert 12-hour hh:mm AM/PM to 24-hour hh:mm 如果用户的机器使用 12 小时制(上午/下午)或 24 小时制(军用时间),则使用 javascript 检测 - Detect with javascript if user's machine is using 12 hour clock (am/pm) or 24 clock (military time) 在骨干/ Javascript中按24小时制对时间进行自定义排序 - Custom Sorting By 24-hour clock Time in Backbone/Javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM