Intl.DateTimeFormat() - return weekday as number?

30 Views Asked by At

It appears Intl.DateTimeFormat() only accepts "narrow", "short", "long" as the weekday option. I would like it to return as a number. i.e. Sunday = 0, Monday = 1 and so on. If I'm correct in reading "numerical" is not an option, what would be an easy way to return the value weekday as a number?

const day = new Intl.DateTimeFormat('en-US', {
    timeZone: America/New_York,
    weekday: 'long',
});

const weekdayNumber = ["0", "1", "2", "3", "4", "5", "6"];
const dayNumber = weekdayNumber[day.format(now)];
console.log('Weekday: ' + dayNumber); // returns error
1

There are 1 best solutions below

1
connexo On BEST ANSWER

Easy way would be Date.prototype.getDay():

const dayNumber = new Date().getDay();

console.log(dayNumber);

If by all means you want to use something to "look it up", this would be one approach to get the weekday as a number:

const day = new Intl.DateTimeFormat('en-US', {
    timeZone: 'America/New_York',
    weekday: 'long',
});

const weekdays = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"];
const dayNumber = weekdays.indexOf(day.format(Date.now()));

console.log(dayNumber);