使用moment.js查找给定工作日(即星期一)的下一个实例 [英] Find next instance of a given weekday (ie. Monday) with moment.js
问题描述
我想知道下周一或周四的日期(如果是周一或周四,则为今天)。由于Moment.js在星期日 - 星期六的范围内工作,我必须计算当天的时间并根据以下内容计算下周一或周四:
I want to get the date of the next Monday or Thursday (or today if it is Mon or Thurs). As Moment.js works within the bounds of a Sunday - Saturday, I'm having to work out the current day and calculate the next Monday or Thursday based on that:
if (moment().format("dddd")=="Sunday") { var nextDay = moment().day(1); }
if (moment().format("dddd")=="Monday") { var nextDay = moment().day(1); }
if (moment().format("dddd")=="Tuesday") { var nextDay = moment().day(4); }
if (moment().format("dddd")=="Wednesday") { var nextDay = moment().day(4); }
if (moment().format("dddd")=="Thursday") { var nextDay = moment().day(4); }
if (moment().format("dddd")=="Friday") { var nextDay = moment(.day(8); }
if (moment().format("dddd")=="Saturday") { var nextDay = moment().day(8); }
这有效,但肯定有更好的方法!
This works, but surely there's a better way!
推荐答案
这里的诀窍不在于使用Moment去特定的从今天开始。它正在推广它,所以你可以随时使用它,无论你在哪一周。
The trick here isn't in using Moment to go to a particular day from today. It's generalizing it, so you can use it with any day, regardless of where you are in the week.
首先你需要知道你在哪里本周: moment.day()
,或稍微更可预测(尽管有语言环境) moment()。isoWeekday()
。
First you need to know where you are in the week: moment.day()
, or the slightly more predictable (in spite of locale) moment().isoWeekday()
.
用它来知道今天是小于还是大于你想要的那天。如果它更小/相等,你可以简单地使用本周的实例星期一或星期四......
Use that to know if today's day is smaller or bigger than the day you want. If it's smaller/equal, you can simply use this week's instance of Monday or Thursday...
const dayINeed = 4; // for Thursday
const today = moment().isoWeekday();
if (today <= dayINeed) {
return moment().isoWeekday(dayINeed);
}
但是,如果今天比我们想要的那天更大,你想要使用下周的同一天:下周一的星期一,无论你在当周的哪个地方。简而言之,你想首先进入下周,使用 moment()。add(1,'weeks')
。一旦你下周,你可以使用 moment()。day(1)
选择你想要的日子。
But, if today is bigger than the day we want, you want to use the same day of next week: "the monday of next week", regardless of where you are in the current week. In a nutshell, you want to first go into next week, using moment().add(1, 'weeks')
. Once you're in next week, you can select the day you want, using 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
这篇关于使用moment.js查找给定工作日(即星期一)的下一个实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!