从周一到周日需要一系列日期



我有一个函数,它可以获取任何输入日期的一周中的所有日期。我稍后会使用它来渲染日历。

然而,日期从周日到周六,而我希望日期从周一到周日。我觉得这是一个很容易的改变,但我似乎想不通。

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()))

正如Kooilnc所说,获取上一个星期一,并构建一个包含7个日期的数组。下面是一个使用基本JS的例子,它可能比纯粹为了避免循环而生成大量不必要的数组更有效。

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'));

查找给定Date的上一个或下一个星期一,并创建一个数组,其中包含从找到的星期一开始的7个后续日期。

Fork这个stackblitz项目来使用这个代码的修改版本。

const mondays = {
next: d => d.getDay === 1 ? 
d : new Date(+d + 
( Math.abs( d.getDay() - (d.getDay() === 0 ? 1 : 8) ) * 864e5 ) ),
previous: d => d.getDay === 1 ? d : new Date(+d - (d.getDay()-1) * 864e5),
};
const toUtc = d => new Date(d.toUTCString());
const getMonday = (d, next) => next ? mondays.next(d) : mondays.previous(d);
const createWeek = (maybeMonday, next) => 
[toUtc(getMonday(maybeMonday, next)),0,0,0,0,0,0]
.map( (_, i, s) => new Date((i * 864e5) + +s[0]) );
// demo
const locale = `en-GB`;
const tls = dates => 
dates.map((d, i) => d.toLocaleDateString(locale)).join(`n`);
const now = new Date();
const then = new Date(1927,2,15);
console.log(`Current week for ${
now.toLocaleDateString(locale)} (today)n${tls(createWeek(now))}`);
console.log(`Current week for ${
then.toLocaleDateString(locale)}n${tls(createWeek(then))}`);
console.log(`Week ahead for ${
now.toLocaleDateString(locale)} (today)n${
tls(createWeek(now, true))}`);
console.log(`Week ahead for ${
then.toLocaleDateString(locale)}n${tls(createWeek(then, true))}`);

/*
notes:
- 864e5 is the number of milliseconds of one day
- uses utc date to prevent time zone surprises
*/
.as-console-wrapper {
max-height: 100% !important;
}

最新更新