Reputation: 73
For a scheduling application, I need to display the weekdays by week numbers starting on Mondays. So far I got to:
var options = {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
};
const weekDays = [];
for (let index = 1; index < 7; index++) {
weekDays.push(new Date(year, 0, index + (week - 1) * 7).toLocaleDateString('nl-NL', options));
}
This code displays a range of dates given by a week and year, but can't seem to get it to start on mondays. Any ideas am I missing something ?
Upvotes: 2
Views: 1037
Reputation: 3327
You're assuming that January 1st of each year starts on a monday. This piece of code automatically finds the first monday of each year.
var year = 2016;
var week = 1;
var index = 1;
var options = {
weekday: 'long',
year: 'numeric',
month: 'long',
day: 'numeric'
};
var d = new Date(year, 0, index + (week - 1) * 7);
var weekday = d.getDay();
var diff = 1 - weekday;
if (diff < 0) {
diff = diff + 7;
}
d.setDate(d.getDate() + diff);
console.log(d.toLocaleString(undefined, options));
Upvotes: 1