How to Get ISO-8601 Numeric Representation of the Day of the Week in JavaScript?

Find out how you can get the day of the week in ISO-8601 format using JavaScript

As per the ISO-8601 format, weekdays are numbered 1 through 7 (where 1 represents Monday and 7 represents Sunday). This is different from the return value of the JavaScript Date.prototype.getDay() method, which returns an integer between 0 and 6 (where 0 represents Sunday and 6 represents Saturday). To make the it compliant with ISO-8601 format, you could simply return 7 when it's Sunday (i.e. when getDay() returns 0), for example, like so:

const dt = new Date();
const day = dt.getDay();
const dayISO8601 = (day === 0 ? 7 : day);

console.log(dayISO8601); // 1 - 7

With that, you could also create a simple reusable function:

function getWeekdayISO8601(dateStr) {
    const dt = new Date(dateStr);
    const day = dt.getDay();
    return (day === 0 ? 7 : day);
}

console.log(getWeekdayISO8601('2021-04-05')); // 1
console.log(getWeekdayISO8601('2021-04-07')); // 3
console.log(getWeekdayISO8601('2021-04-11')); // 7

Hope you found this post useful. It was published . Please show your love and support by sharing this post.