Moment.js, Get next [weekday]

2019-09-11 20:49发布

Trying to get second coming Thursday (e.g.) using moment.js. Not this Thursday. The next one. The date in 2 Thursdays.

I have tried

moment().add(1, 'week').day(4)

which just fetches Thursday of the next week (only works if current weekday is before Thursday)

Any ideas?

2条回答
可以哭但决不认输i
2楼-- · 2019-09-11 20:55

"which just fetches Thursday of the next week (only works if current weekday is before Thursday)"

It's happening because .add(1, 'week') just adds 7 days and gets you the next week date and you are fetching 4th day of that week. Below code will work for your case perfectly.

if(moment().weekday() < 4)
 moment().add(1, 'week').day(4);
else
 moment().add(2, 'week').day(4);
查看更多
ゆ 、 Hurt°
3楼-- · 2019-09-11 21:11

Not sure about using moment.js, but in plain js next Thursday is given by:

currentDate + (11 - d.getDay() % 7)

For the following Thursday, just add 7 days. Presumably if the current day is Thursday, want the Thursday in two weeks so:

var d = new Date();
console.log(d.toString());

// Shift to next Thursday
d.setDate(d.getDate() + ((11 - d.getDay()) % 7 || 7) + 7)
console.log(d.toString())

Or encapsulated in a function with some tests:

function nextThursdayWeek(d) {
  d = d || new Date();
  d.setDate(d.getDate() + ((11 - d.getDay()) % 7 || 7) + 7);
  return d;
}

// Test data
[new Date(2017,2,6),  // Mon  6 Mar 2017
 new Date(2017,2,7),  // Tue  7 Mar 2017
 new Date(2017,2,8),  // Wed  8 Mar 2017
 new Date(2017,2,9),  // Thu  9 Mar 2017
 new Date(2017,2,10), // Fri 10 Mar 2017
 new Date(2017,2,11), // Sat 11 Mar 2017
 new Date(2017,2,12), // Sun 12 Mar 2017
 new Date()           // Today
].forEach(function (date) {
  console.log(date.toString() + ' -> ' + nextThursdayWeek(date).toString());
});

查看更多
登录 后发表回答