Get localized short names of days of week from monday to sunday in JavaScript

245 Views Asked by At

How can I get localized short names of the days of the week, starting from monday to sunday, in JavaScript?

3

There are 3 best solutions below

0
Matthieu Chavigny On

Here is an example with a French locale:

const locale = "fr-fr";
const shortNames = [];
const formatter = new Intl.DateTimeFormat(locale, {
  weekday: 'short'
});
const today = new Date();
const startDay = 1; // Monday
for (let day = startDay; day < startDay + 7; day++) {
  const date = new Date(today);
  date.setDate(today.getDate() + ((day - today.getDay() + 7) % 7));
  const formattedParts = formatter.formatToParts(date);
  const shortName = formattedParts.find(part => part.type === 'weekday').value;
  shortNames.push(shortName);
}
console.log(shortNames);

0
Matthieu Chavigny On

Another example with long names in English:

const locale = "en-us";
const longNames = [];
const formatter = new Intl.DateTimeFormat(locale, {
  weekday: 'long'
});
const today = new Date();
const startDay = 1; // Monday
for (let day = startDay; day < startDay + 7; day++) {
  const date = new Date(today);
  date.setDate(today.getDate() + ((day - today.getDay() + 7) % 7));
  const formattedParts = formatter.formatToParts(date);
  const longName = formattedParts.find(part => part.type === 'weekday').value;
  longNames.push(longName);
}
console.log(longNames);

0
RobG On

You seem to be overcomplicating things. You can initialise the date used for getting the day names to a date that is the day you want to start on. Also, toLocaleString is simpler and accepts the same options as DateTimeFormat without the overhead.

Here's a simple for loop version:

function getShortWeekdayNames(lang) {
  let days = [];
  for (let d = new Date(2023,5,12), i=7; i; --i) {
    days.push(d.toLocaleString(lang, {weekday:'short'}));
    d.setDate(d.getDate() + 1);
  }
  return days;
}

console.log(getShortWeekdayNames('fr'));

And a more obfuscated one-liner:

let getShortWeekdayNames = lang => new Array(7).fill(0).map((x, i) => new Date(1,0,i).toLocaleString(lang, {weekday:'short'}));

console.log(getShortWeekdayNames('ar'));

If you play with it a little more, you can have the caller specify the first day of the week as the ECMAScript day number and use that when initialising the date:

let getShortWeekdayNames = (lang, d=1) => new Array(7).fill(0).map((x, i) => new Date(1,3,i+d).toLocaleString(lang, {weekday:'short'}));

// Monday start (default)
console.log(getShortWeekdayNames('en').join());
// Sunday start
console.log(getShortWeekdayNames('en', 0).join());
// Saturday start
console.log(getShortWeekdayNames('en', 6).join());