1

Searching for this didn't bear much fruit. Hopefully you can help!

I'm looking to generate sentences like this:

The next Monday session starts on Monday October 19th[1] and runs for 7 weeks until Monday November 30th[2]

where [1] is the date of the next Monday, unless that Monday is 4 days or less in the future, in which case it will be the following Monday. And, [2] is 7 weeks after the Monday mentioned in [1].

As a bonus if it worked for other days of the week it would be awesome!

The dates can be based on the client browser. I'm hoping to implement this entirely in client side JS for a website.

Any help or pointers in the right direction?

Emiel Zuurbier
  • 19,095
  • 3
  • 17
  • 32
Eric Warnke
  • 1,325
  • 12
  • 18
  • 1
    If you haven't tried anything yet then look at the [`Date`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date) object or a framework like Moment.js to parse dates. Try something out and come back anytime you get stuck or got questions about it. – Emiel Zuurbier Oct 21 '20 at 20:22
  • Does this answer your question? [Getting the date of next Monday](https://stackoverflow.com/questions/33078406/getting-the-date-of-next-monday) Combine that with [Compare two date in JavaScript](https://stackoverflow.com/q/492994/215552) and [How to add weeks to date using javascript?](https://stackoverflow.com/q/11343939/215552)... – Heretic Monkey Oct 21 '20 at 20:26

1 Answers1

1

let date = new Date();
let nextMonday = new Date();
let daysToNextMonday = new Date();

nextMonday.setDate(date.getDate() + (1 + 7 - date.getDay() % 7));
let diffTime = Math.abs(nextMonday - date);

daysToNextMonday = Math.ceil(diffTime / (1000 * 60 * 60 * 24)); //full days, no fractions


if (daysToNextMonday <= 4) {
  nextMonday.setDate(nextMonday.getDate() + 7);
}

let sevenWeeksAfter = new Date(nextMonday);
sevenWeeksAfter.setDate(nextMonday.getDate() + 7 * 7);

const monthNextMonday = new Intl.DateTimeFormat('en', {
  month: 'long'
}).format(nextMonday);
const dayNextMonday = new Intl.DateTimeFormat('en', {
  day: '2-digit'
}).format(nextMonday);

const monthSevenWeeksAfter = new Intl.DateTimeFormat('en', {
  month: 'long'
}).format(sevenWeeksAfter);
const daySevenWeeksAfter = new Intl.DateTimeFormat('en', {
  day: '2-digit'
}).format(sevenWeeksAfter);

let text = `The next Monday session starts on Monday ${monthNextMonday} ${dayNextMonday}th and runs for 7 weeks until Monday ${monthSevenWeeksAfter} ${daySevenWeeksAfter}th`;

console.log(text);
MWO
  • 2,627
  • 2
  • 10
  • 25