skip to Main Content

How to get localized short names of the days of week starting from monday to sunday in javascript?

3

Answers


  1. Chosen as BEST ANSWER

    Here is example with 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);


  2. 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);
    Login or Signup to reply.
  3. You seem to be over complicating 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());
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search