javascriptarraysdayofweekweekday

How do can I GET AN ARRAY OF ALL WEEKDAYS in javascript


My application includes Java 21 on the server side and React.js on the client side. According to the Locale, I must get a list/array of weekdays. I have no limits on dependencies to use, as long as they are free/open-source.

I can do that in Java using the following code (didn't invest too much time writing it) and calling an API from the client to get it, but I want something that is JavaScript and if I can save the API request:

String[] weekDays = DateFormatSymbols.getInstance().getWeekdays();
System.out.print("weekDays:\n\t");
Arrays.stream(weekDays).forEach(x -> System.out.print(x + ", "));
System.out.println();

**Output:**
daysOfWeek:
    , Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday, 

The code in Java for weekdays in German:

    String[] daysOfWeekGER = DateFormatSymbols.getInstance(Locale.GERMAN).getWeekdays();
    System.out.print("daysOfWeekGER:\n\t");
    Arrays.stream(daysOfWeekGER).forEach(x -> System.out.print(x + ", "));
    System.out.println();
    
    **Output**
    daysOfWeekGER:
        , Sonntag, Montag, Dienstag, Mittwoch, Donnerstag, Freitag, Samstag, 

I am looking for something similar in JavaScript.

This question is NOT a duplicate for Getting localized day of week as my question is about getting a list of all weekdays depending on the Locale vs that question.

I searched for similar questions before creating this one, as I need and want a solution. I read my question carefully before flagging it as a duplicate, as I couldn't find any on StackOverflow.

My Requirements For The Solution:

  1. Generate an array of weekdays depending on Locale.
  2. The Locale affects the names of the weekdays.
  3. The Locale affects the list of weekdays, whether the first weekday is Saturday, Sunday, or Monday.
  4. No data should be hard-coded (it will affect development, tests, and maintenance).

Java code for similar requirements This example includes the code above.

Yes, I know that new Locale(stringLanguage, stringCountry) is deprecated from Java 19, and in Java 22+ I need to use Locale.of(stringLanguage, stringCountry).

The result MUST be AN ARRAY OF STRINGS containing the weekdays' full names, a SINGLE STRING is not a valid solution. I know how to get the weekday name of a specific date—that's not the question.

Creating a hardcoded array for every language is impractical and wastes time and effort.

If there's no solution, I will do it on the Java server, and the React.js client will call an API endpoint to receive it.


Solution

  • You could use Intl.DateTimeFormat:

    function getLocalizedWeekdays(locale) {
      const formatter = new Intl.DateTimeFormat(locale, { weekday: 'long' });
      return [...Array(7).keys()].map((dayIndex) => {
        // January 1st 2024 is a Sunday in UTC.
        const date = new Date(
          Date.UTC(/*year=*/2024, /*monthIndex=*/0, /*day=*/1 + dayIndex),
        );
        return formatter.format(date);
      });
    }
    
    console.log('"en-US" =', getLocalizedWeekdays('en-US'));
    console.log('"de-DE" =', getLocalizedWeekdays('de-DE'));
    .as-console-wrapper { max-height: 100% !important; top: 0; }


    Extended answer to dynamically get the first day of the week based on country, as requested by OP in the comments.

    As far as I can tell, there is no robust way in the Javascript standard library to tell which day of the week is the first per country currently (there is this Intl.Locale.prototype.getWeekInfo() however, it has limited availability, notably not working in Firefox yet). So you need to define that mapping yourself or utilize a third-party library like Moment.js:

    function getLocalizedWeekdays(locale) {
      const formatter = new Intl.DateTimeFormat(locale, { weekday: 'long' });
      const firstDayOfWeek = moment.localeData(locale).firstDayOfWeek();
      return [...Array(7).keys()].map((dayIndex) => {
        // January 1st 2024 is a Sunday in UTC.
        const date = new Date(
          Date.UTC(
            /*year=*/2024,
            /*monthIndex=*/0,
            /*day=*/1 + ((firstDayOfWeek + dayIndex) % 7),
          ),
        );
        return formatter.format(date);
      });
    }
    
    console.log('"en-US" =', getLocalizedWeekdays('en-US'));
    console.log('"he-UA" =', getLocalizedWeekdays('he-UA'));
    console.log('"ar-FR" =', getLocalizedWeekdays('ar-FR'));
    console.log('"es-IL" =', getLocalizedWeekdays('es-IL'));
    console.log('"en-NZ" =', getLocalizedWeekdays('en-NZ'));
    console.log('"de-DE" =', getLocalizedWeekdays('de-DE'));
    .as-console-wrapper { max-height: 100% !important; top: 0; }
    <script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.30.1/moment-with-locales.min.js"></script>