Search code examples
javascriptweekday

Javascript get localized weekday without a DateTime object


I at the moment have the day values as strings. (e.g. "monday", "tuesday", "wednesday", "thursday", "friday", "saturday", "sunday") but no date.

The days describe opening hours of a shop and I would like to translate these string values dynamically based of the locale set on the shop.

I noticed that JS have the wonderful method Date.prototype.toLocaleDateString() but it doesn't seem like that I can get the localized string without providing a date. How would you go about this?


Solution

  • You can create a dummy date based on the weekday, choosing the year and month such that a day value of 0 matches a Sunday (yes, you can specify the 0th day too).

    Then you can use toLocaleDateString with the date to ask for the translated weekday string.

    (I also invoked an Intl.DateTimeFormatter here to get the user's default locale, because we cannot specify an options object without also specifying a locale.)

    const WEEKDAYS = ['sunday', 'monday', 'tuesday', 'wednesday', 'thursday', 'friday', 'saturday']
    
    function translateWeekday (weekdayString) {
      const weekdayIndex = WEEKDAYS.indexOf(weekdayString.toLowerCase())
      if (weekdayIndex < 0) throw new Error(`Unknown weekday "${weekdayString}"`)
    
      const dummyDate = new Date(2001, 0, weekdayIndex)
      const locale = new Intl.DateTimeFormat().resolvedOptions().locale
    
      return dummyDate.toLocaleDateString(locale, { weekday: 'long' })
    }
    

    On my machine with German locale, translateWeekday('Wednesday') returns 'Mittwoch' for example.