如何使用 Intl 获取工作日名称?

How to get the weekday names using Intl?

我想在我的 i18n-ed 应用程序中显示 7 个工作日的列表:

Sunday, Monday, Tuesday... Saturday

我依靠 Intl global object 来格式化 date/time,但我找不到一种简单的方法来 工作日名称。

我想我可以在 EPOCH 时间上增加一些天数,以到达一周的第一天,但​​我找不到只打印工作日的格式化程序。

var date = new Date(0);
date.setDate(4 + day);
for (var i = 0; i < 7; i++) {
  var weekday = new Intl.DateTimeFormat(["en"], {
      weekday: "short" // ?? what should I put here
  }).format(date);
  console.log(weekday);
}

输出:

Sunday, January 4, 1970
Monday, January 5, 1970
Tuesday, January 6, 1970
Wednesday, January 7, 1970
Thursday, January 8, 1970
Friday, January 9, 1970
Saturday, January 10, 1970

期望的输出:

Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday

我也想有更短版本的日子,比如Sun, Mon, Tue...

或者,有没有办法从 Intl 获取工作日 strings?我试图通过控制台探索该对象,但找不到它们。

我被误导了,因为我使用的是 Intl polyfill,它还不支持 { weekday: "short" } 作为选项。

使用本机 Intl 实现按预期工作。

Intl(因此 Intl.js 也一样)还没有 API 来获取工作日名称,因此您必须执行查询 a 的 hack-thing有正确选择的几天。有可能 add support for doing so in the future,但现在你基本上不走运了。 (至少,除非您通过修复手动扩充 Intl.js。)

 const weekdayDateMap = {
  Mon: new Date('2020-01-06T00:00:00.000Z'),
  Tue: new Date('2020-01-07T00:00:00.000Z'),
  Wed: new Date('2020-01-08T00:00:00.000Z'),
  Thu: new Date('2020-01-09T00:00:00.000Z'),
  Fri: new Date('2020-01-10T00:00:00.000Z'),
  Sat: new Date('2020-01-11T00:00:00.000Z'),
  Sun: new Date('2020-01-12T00:00:00.000Z'),
};
const shortWeekdays = Object.keys(weekdayDateMap);

const getDayOfWeek = (shortName, locale = 'en-US', length = 'short') =>
  new Intl.DateTimeFormat(locale, { weekday: length }).format(weekdayDateMap[shortName]);

const getDaysOfWeek = (locale = 'en-US', length = 'short') =>
  shortWeekdays.map(shortName => getDayOfWeek(shortName, locale, length));


console.log(getDayOfWeek('Mon', 'de-DE')) // "Mo"

console.log(getDaysOfWeek('de-DE')) // ["Mo", "Di", "Mi", "Do", "Fr", "Sa", "So"]

注:

如果您每秒多次调用 Intl.DateTimeFormat 格式化程序,创建一次格式化程序并重新使用它会更有效。

我在 2021 年使用 es6 的解决方案

/**
 * Return list of days
 *  localeName : name of local, f.e. en-GB, default es-MX
 *  ✅ weekday   : formart of weekday short/long (Default)
 */
function daysForLocale(localeName = 'es-MX', weekday = 'long') {
  const format = new Intl.DateTimeFormat(localeName, { weekday }).format;
  return [...Array(7).keys()]
    .map((day) => format(new Date(Date.UTC(2021, 5, day))));
}

// ##############################################################
// testing daysForLocale function
// ##############################################################
console.log(daysForLocale());
// ['domingo','lunes',...,'viernes','sábado']
console.log(daysForLocale('en-GB', 'short'));
// ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri','Sat']
console.log(daysForLocale('ja-JP', 'short'));
// ['日', '月', '火','水', '木', '金','土']

更简单的解决方案:

let d = new Date();
let day_options = {
    timeZone: "America/New_York",
    weekday:"short"
};
let formatter = new Intl.DateTimeFormat([],day_options);
console.log(formatter.format(d));

输出:周四