I'd like to display in my i18n-ed app a list of the 7 weekdays:
Sunday, Monday, Tuesday... Saturday
I rely on the Intl global object for formatting date/time but I can't find an easy way to get only the weekday names.
I thought I could add some days to the EPOCH time, to reach the first day of the week, but I'm failing to find a formatter printing just the weekday.
var date = new Date(0);
date.setDate(4 + day);
for (var i = 0; i < 7; i++) {
var weekday = new Intl.DateTimeFormat(["en"], {
weekday: "short" // ?? what should I put here
}).format(date);
console.log(weekday);
}
Output:
Sunday, January 4, 1970
Monday, January 5, 1970
Tuesday, January 6, 1970
Wednesday, January 7, 1970
Thursday, January 8, 1970
Friday, January 9, 1970
Saturday, January 10, 1970
Desired output:
Sunday
Monday
Tuesday
Wednesday
Thursday
Friday
Saturday
I also would like to have a shorter version of the days, such as Sun, Mon, Tue...
.
Alternatively, is there a way to get the weekday strings from Intl
? I tried to explore the object via console but I couldn't find them.
I was misled because I was using the Intl polyfill, which does not support yet { weekday: "short" }
as option.
Using native Intl implementations works as expected.
/**
* Return list of days
* 🌍 localeName : name of local, f.e. en-GB, default es-MX
* ✅ weekday : formart of weekday short/long (Default)
*/
function daysForLocale(localeName = 'es-MX', weekday = 'long') {
const format = new Intl.DateTimeFormat(localeName, { weekday }).format;
return [...Array(7).keys()]
.map((day) => format(new Date(Date.UTC(2021, 5, day))));
}
// ##############################################################
// testing daysForLocale function
// ##############################################################
console.log(daysForLocale());
// ['domingo','lunes',...,'viernes','sábado']
console.log(daysForLocale('en-GB', 'short'));
// ['Sun', 'Mon', 'Tue', 'Wed', 'Thu', 'Fri','Sat']
console.log(daysForLocale('ja-JP', 'short'));
// ['日', '月', '火','水', '木', '金','土']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With