admin管理员组

文章数量:1410674

Trying to get second ing 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?

Trying to get second ing 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?

Share Improve this question edited Mar 5, 2017 at 21:24 softcode asked Mar 5, 2017 at 19:23 softcodesoftcode 4,68812 gold badges44 silver badges69 bronze badges 11
  • have you looked at the .weekday() property? – Jhecht Commented Mar 5, 2017 at 21:11
  • @Jhecht I have, what about it? – softcode Commented Mar 5, 2017 at 21:14
  • Why doesn't weekday work for what you need? – Jhecht Commented Mar 5, 2017 at 21:14
  • 1 possibly duplicate of stackoverflow./questions/31476817/momentjs-next-business-day – andrepaulo Commented Mar 5, 2017 at 21:15
  • @andrepaulo No man, next business day is easy. I'm trying to get the second instance of the weekday – softcode Commented Mar 5, 2017 at 21:16
 |  Show 6 more ments

2 Answers 2

Reset to default 4

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

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

本文标签: javascriptmomentjsGet next weekdayStack Overflow