Mik*_*ell 37 javascript momentjs
我希望得到下周一或周四的日期(如果是周一或周四,则为今天).由于Moment.js在星期日 - 星期六的范围内工作,我必须在当天计算并根据以下计算下周一或周四:
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); }
Run Code Online (Sandbox Code Playgroud)
这有效,但肯定有更好的方法!
XML*_*XML 73
这里的诀窍不在于使用Moment从今天起到特定的一天.它正在推广它,所以你可以随时使用它,无论你在哪一周.
首先,你需要知道你在一周的位置:moment.day()或者稍微更可预测(尽管有语言环境)moment().isoWeekday().
用它来知道今天是否比你想要的那天更小或更大.如果它更小/相等,你可以简单地使用本周的周一或周四的实例......
const dayINeed = 4; // for Thursday
const today = moment().isoWeekday();
if (today <= dayINeed) {
return moment().isoWeekday(dayINeed);
}
Run Code Online (Sandbox Code Playgroud)
但是,如果今天比我们想要的那天更大,你想要使用下周的同一天:"下周一的星期一",无论你在当周的哪个地方.简而言之,你想先用下周进入下周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);
}
Run Code Online (Sandbox Code Playgroud)
Ash*_*hUK 13
使用时刻获得下一个星期一
moment().startOf('isoWeek').add(1, 'week');
Run Code Online (Sandbox Code Playgroud)
Gav*_*iel 10
moment().day() 会给你一个引用day_of_week的数字.
什么更好:moment().day(1 + 7)并将moment().day(4 + 7)分别在下周一,下周四给你.
查看更多:http://momentjs.com/docs/#/get-set/day/
以下内容可用于从现在(或任何日期)获取下一个工作日日期
var weekDayToFind = moment().day('Monday').weekday(); //change to searched day name
var searchDate = moment(); //now or change to any date
while (searchDate.weekday() !== weekDayToFind){
searchDate.add(1, 'day');
}
Run Code Online (Sandbox Code Playgroud)
小智 5
大多数答案都没有解决OP的问题。Andrejs Kuzmins 的算法是最好的,但我会对其进行更多改进,以便算法考虑到语言环境。
var nextMoOrTh = moment().isoWeekday([1,4,4,4,8,8,8][moment().isoWeekday()-1]);
Run Code Online (Sandbox Code Playgroud)