Search code examples
javascriptdatelocalization

Getting localized day of week


I'd like to get the names of the days of the weeks in JavaScript, localized to the user's current language; preferably with something a bit nicer than what I'm using now:

var weekDays = [];
var d = new Date();

while(d.getDay() > 0) {
    d.setDate(d.getDate() + 1);
}

while(weekDays.length < 7) {
    weekDays.push(d.toLocaleDateString().match(/\w+/)[0]);
    d.setDate(d.getDate() + 1);
}

Is there an easy way to do this? Or am I just going to have to provide date strings for as many locales as I can?


Solution

  • Standard way to translate Date is to use method Date.toLocaleString(), for example:

    d = new Date();
    // short date in browser language
    console.log(d.toLocaleString(window.navigator.language, {
      weekday: 'short'
    }));
    // long date in specific language
    console.log(d.toLocaleString('sk-SK', {
      weekday: 'long'
    }));