这里的技巧不在于使用 Moment 转到今天的某一天。它对其进行了概括,因此您可以在任何一天使用它,无论您在一周中的哪个时间段。
首先,您需要知道您本周在哪里:moment().day()
,或者稍微更可预测的(不管语言环境)moment().isoWeekday()
。重要的是,这些方法返回一个整数,这使得使用比较运算符可以轻松确定您在一周中相对于目标的位置。
用它来知道今天是比您想要的日子小还是大。如果它更小/相等,您可以简单地使用本周星期一或星期四的实例......
const dayINeed = 4; // for Thursday
const today = moment().isoWeekday();
if (today <= dayINeed) {
return moment().isoWeekday(dayINeed);
}
但是,如果今天比我们想要的日子大,您想使用同一天下周:“下周的星期一”,无论您本周位于何处。简而言之,您想首先进入下周,使用moment().add(1, 'weeks')
。进入下周后,您可以使用以下方法选择您想要的日期moment().day(1)
.
一起:
const dayINeed = 4; // for Thursday
const today = moment().isoWeekday();
// if we haven't yet passed the day of the week that I need:
if (today <= dayINeed) {
// then just give me this week's instance of that day
return moment().isoWeekday(dayINeed);
} else {
// otherwise, give me *next week's* instance of that same day
return moment().add(1, 'weeks').isoWeekday(dayINeed);
}
也可以看看https://stackoverflow.com/a/27305748/800457
编辑:其他评论者指出,OP想要比这更具体的东西:值数组的下一个(“下周一或周四”),而不仅仅是任意一天的下一个实例。嗯不错。
通解是总解的开始。我们不是比较一天,而是比较一系列天:[1,4]
:
const daysINeed = [1,4]; // Monday, Thursday
// we will assume the days are in order for this demo, but inputs should be sanitized and sorted
function isThisInFuture(targetDayNum) {
// param: positive integer for weekday
// returns: matching moment or false
const todayNum = moment().isoWeekday();
if (todayNum <= targetDayNum) {
return moment().isoWeekday(targetDayNum);
}
return false;
}
function findNextInstanceInDaysArray(daysArray) {
// iterate the array of days and find all possible matches
const tests = daysINeed.map(isThisInFuture);
// select the first matching day of this week, ignoring subsequent ones, by finding the first moment object
const thisWeek = tests.find((sample) => {return sample instanceof moment});
// but if there are none, we'll return the first valid day of next week (again, assuming the days are sorted)
return thisWeek || moment().add(1, 'weeks').isoWeekday(daysINeed[0]);;
}
findNextInstanceInDaysArray(daysINeed);
我会注意到,后来的一些海报提供了一个非常精简的解决方案,对有效数值数组进行硬编码。如果您总是期望在同一天进行搜索,并且不需要概括其他搜索,那就更合适了计算地有效的解决方案,尽管不是最容易阅读的,并且不可能扩展。