I have a function that gets all days of any input dates's week. I use this later on to render a calendar.
However, the dates go from Sunday-Saturday when I want them going from Monday-Sunday. I feel like the would be an easy change but I can't seem to figure it out.
const createNewWeek = (startDate) => {
const newDates = Array.from(Array(7).keys()).map((idx) => {
const d = new Date(startDate);
d.setDate(d.getDate() - d.getDay() idx);
return d;
})
return newDates
}
console.log(createNewWeek(new Date()))
CodePudding user response:
Find previous monday for a given Date
and create an array with 7 subsequent dates starting with the found monday.
Fork this stackblitz project to play with this code.
const getMonday = d => new Date(d - (d.getDay()-1) * 864e5);
const dow = d => [`su`, `mo`, `tu`, `we`, `th`, `fr`, `sa`]
.find( (_, i) => d === i);
const createNewWeek = maybeMonday => [...Array(6)]
.reduce( (acc, d, i) =>
[...acc, new Date( acc[0] (i 1) * 864e5)],
[getMonday(new Date(maybeMonday.toUTCString()))] )
.map( d => `${dow(d.getDay())} ${d.toLocaleDateString()}` );
const now = new Date();
const then = new Date(1927,2,15)
console.log(`This week from ${now.toLocaleDateString()}\n`,
createNewWeek(now));
console.log(`Another week from ${then.toLocaleDateString()}\n`,
createNewWeek(then));
/*
notes:
- 864e5 is the number of milliseconds of one day
- uses utc date to prevent time zone surprises
- The reducer is sufficient to create the array of dates
(so map and dow function are only for this snippet).
*/
.as-console-wrapper {
max-height: 100% !important;
}
CodePudding user response:
As Kooilnc says, get the previous Monday and build an array of 7 dates. The following is an example using basic JS that is likely much more efficient than generating lots of unnecessary arrays purely for the sake of avoiding a boring old for loop.
function getMonToSun(date = new Date()) {
// Result array
let week = [];
// Prior Monday
let mon = new Date(date.getFullYear(), date.getMonth(),
date.getDate() - (date.getDay() || 7) 1);
// Build array of 7 dates from Monday
for (let i=0; i<7; i ) {
week.push(new Date(mon.getFullYear(), mon.getMonth(), mon.getDate() i));
}
return week;
}
// Current week
console.log(getMonToSun().join('\n'));
// Week of 1 Jan 2000
console.log(getMonToSun(new Date(2000,0,1)).join('\n'));