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
This post was published by Daniyal Hamid. Daniyal currently works as the Head of Engineering in Germany and has 20+ years of experience in software engineering, design and marketing. Please show your love and support by sharing this post.