Reputation: 224942
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?
Upvotes: 26
Views: 30340
Reputation: 2769
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'
}));
Upvotes: 64
Reputation:
Take a look at datejs, it handles localization very nicely. It comes with a lot of globalization setups. You just load the globalization setup of your current CultureInfo and datejs takes care of the rest.
Upvotes: 2