简体   繁体   English

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

[英]Detect if user's locale is set to 12-hour or 24-hour timeformat using javascript

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.如何使用 Javascript 检查用户是否使用 12 小时或 24 小时时间格式,有或没有使用像 moment.js 这样的第三方库我也尝试new Date().toLocaleString()但它没有在 firefox 和谷歌浏览器中测试。 firefox always shows 12hr format and chrome always shows 24hrs time format firefox 始终显示 12 小时制,而 chrome 始终显示 24 小时制

Something like this:像这样的东西:

/*
 * 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(undefined, { hour: 'numeric' }).format(0).match(/\s/);

Check browser compatibility of Intl.DateTimeFormat .检查Intl.DateTimeFormat 的浏览器兼容性。

You can perhaps fallback to the following, but I'm not sure whether AM/PM designation (whichever characters are used) is at the end of the output for all locales.您也许可以回退到以下内容,但我不确定AM/PM指定(无论使用哪个字符)是否位于所有语言环境的输出末尾。 This just checks whether the last character is numeric:这只是检查最后一个字符是否是数字:

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

Mario Bonaci's answer didn't work as expected for me though it pointed me to the right direction. Mario Bonaci 的回答并没有像我预期的那样奏效,尽管它为我指明了正确的方向。 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/);

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.undefined更改为navigator.language 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/);

@Marko Bonaci's answer was helpful. @Marko Bonaci 的回答很有帮助。 I researched his comment "I'm not sure whether AM/PM designation (whichever characters are used) is at the end of the output for all locales."我研究了他的评论“我不确定 AM/PM 指定(无论使用哪个字符)是否在所有语言环境的输出末尾。” A Google search listed this link stating a user's comment:谷歌搜索列出了这个链接,说明了用户的评论:

The Latin abbreviations am and pm (often written "am" and "pm", "AM" and "PM", or "AM" and "PM") are used in English, Portuguese (Brazilian) and Spanish.拉丁语缩写 am 和 pm(通常写作“am”和“pm”、“AM”和“PM”或“AM”和“PM”)用于英语、葡萄牙语(巴西)和西班牙语。 The equivalents in Greek are π.µ.希腊语中的等价物是 π.µ。 and µ.µ.和µ.µ。 respectively.分别。

This can be verified from the browser's console using the two letter ISO 639-1 code "el" or the three letter ISO 639-2 code "ell":这可以从浏览器的控制台使用两个字母的ISO 639-1代码“el”或三个字母的 ISO 639-2 代码“ell”来验证:

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

These lines will return a value with the localized "AM"/"PM" string:这些行将返回一个带有本地化“AM”/“PM”字符串的值:

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

I ended up using his suggestion using the built-in ' Number ' object in JavaScript.我最终采纳了他的建议,使用了 JavaScript 中的内置“ Number ”对象。

// 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'

Here's my long-winded function:这是我冗长的功能:

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);

Using Intl.Locale().hourCycles使用 Intl.Locale().hourCycles

Lastly, for much newer browser's (except Firefox as of Dec 2022), there's new Intl.Locale(navigator.language).hourCycles listed on MDN .最后,对于更新的浏览器(2022 年 12 月的 Firefox 除外), MDN上列出了新的 Intl.Locale(navigator.language).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

The Intl.Locale.prototype.hourCycle property is an accessor property that returns the time keeping format convention used by the locale. Intl.Locale.prototype.hourCycle 属性是一个访问器属性,它返回语言环境使用的计时格式约定。

There are 2 main types of time keeping conventions (clocks) used around the world: the 12 hour clock and the 24 hour clock.世界上主要使用两种计时约定(时钟):12 小时制和 24 小时制。 The hourCycle property makes it easier for JavaScript programmers to access the clock type used by a particular locale. hourCycle 属性使 JavaScript 程序员更容易访问特定区域设置使用的时钟类型。

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

相关问题 Javascript -- 检测用户的区域设置是否设置为使用 12 小时或 24 小时时间格式 - Javascript -- Detect if user's locale are set to use 12-hour or 24-hour time format 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 根据 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 Moment.js接受12小时和24小时时间 - Moment.js Accept both 12-hour and 24-hour time 如果用户的机器使用 12 小时制(上午/下午)或 24 小时制(军用时间),则使用 javascript 检测 - Detect with javascript if user's machine is using 12 hour clock (am/pm) or 24 clock (military time) 如果用户输入的时间超过24小时,则javascript-report错误 - javascript-report error if user enter time beyond 24-hour JavaScript以12小时格式随机生成时间 - JavaScript random generate time in 12-hour format
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM