HTML5 Intl API每周的第一天

Dav*_*der 7 javascript html5 date internationalization ecmascript-intl

有没有办法从HTML5国际化API获取一周的第一天(大多数国家的周日或周一)?

规范可以在这里找到.如果它没有以某种方式披露我会感到惊讶,但我似乎无法找到它.

Jef*_*den 6

Intl还没有访问此类日历信息的 API。它可能会在未来增加对这样做的支持,但现在你不走运。


Leo*_*ler 5

用于检索此信息的官方普通 API 是Locale.prototype.getWeekInfo(),或者当前更受支持的Locale.prototype.weekInfo(Firefox 也不支持!):

小提示:Firefox 也不支持!

// New API, currently only in Deno, Bun & Safari Technology Preview (2023-10)
new Intl.Locale('en-US').getWeekInfo()

// "Old" API, available in Chrome, Edge, Opera, Node & other Chromium-based browsers
new Intl.Locale('en-US').weekInfo
Run Code Online (Sandbox Code Playgroud)

它将返回一个像这样的对象:

{
    firstDay: 7,      // First day of the week is Sunday
    minimalDays: 1,   // First calendar week of the year must have at least 1 weekday
    weekend: [6, 7]   // Weekend is Saturday and Sunday
}
Run Code Online (Sandbox Code Playgroud)

其他文化的示例:( new Intl.Locale('<locale>').weekInfo)

德国de-DE

{
    firstDay: 1,      // First day of the week is Monday
    minimalDays: 4,   // First calendar week of the year has at least 4 weekdays
    weekend: [6, 7]   // Weekend is Saturday and Sunday
}
Run Code Online (Sandbox Code Playgroud)

埃及ar-EG:

{
    firstDay: 6,      // First day of the week is Saturday
    minimalDays: 1,   // First calendar week of the year has at least 1 weekday
    weekend: [5, 6]   // Weekend is Friday and Saturday
}
Run Code Online (Sandbox Code Playgroud)

乌干达sw-UG:

{
    firstDay: 1,      // First day of the week is Monday
    minimalDays: 1,   // First calendar week of the year has at least 1 weekday
    weekend: [7]      // Weekend is Sunday only
}
Run Code Online (Sandbox Code Playgroud)

文莱ms-BN

{
    firstDay: 7,      // First day of the week is Sunday
    minimalDays: 1,   // First calendar week of the year has at least 1 weekday
    weekend: [5, 7]   // Weekend is Friday and Sunday
}
Run Code Online (Sandbox Code Playgroud)

Polyfilling 这是可能的,但我推荐优秀的date-fns库,直到TemporalAPI 到达大多数浏览器,它具有适用于当前 93 个语言环境的类似数据(没有周末信息):

import { enUS, deAT, ar, hi } from 'date-fns/locale'

enUS.options.weekStartsOn          // 0 <- careful, 0 = Sunday
enUS.options.firstWeekContainsDate // 1

deAT.options.weekStartsOn          // 1
deAT.options.firstWeekContainsDate // 4

// Arabic
ar.options.weekStartsOn            // 6
ar.options.firstWeekContainsDate   // 1

// Hindi
hi.options.weekStartsOn            // 0
hi.options.firstWeekContainsDate   // 4
Run Code Online (Sandbox Code Playgroud)

小注意事项 - 规范已从属性更改为函数,因为所有浏览器/运行时都实现weekInfo为 getter,它总是返回一个新对象,并导致这种不直观的行为:

const swedish = new Intl.Locale('sv');
swedish.weekInfo === swedish.weekInfo  // false
Run Code Online (Sandbox Code Playgroud)

  • 我在“weekInfo”上找到的一些信息:当它存在时会很棒,但是 [intl-locale-info](https://github.com/tc39/proposal-intl-locale-info) 的 TC39 提案是目前在 firefox 和一些活跃的 safari 版本中处于第 3 阶段并且[尚不可用](https://caniuse.com/mdn-javascript_builtins_intl_locale_weekinfo)。我找不到 Polyfill。 (2认同)