Home > Blockchain >  get nth weekday in the month by day number within that month
get nth weekday in the month by day number within that month

Time:11-30

For a given day in a month (e.g. day 22 of November 2022), I want to be able to find out which number occurrence that particular weekday happens to be within that month. So, given day 22 of November 2022, I need to get back "4th Tuesday".

Ideally I would love to accomplish this with javascript Date or Luxon if possible, but my searching so far hasn't yielded an answer, and the logic to determine this is just escaping me.

Thanks!

CodePudding user response:

This really is a number of questions in one.

You can get the weekday name from toLocaleString with suitable options.

The nth instance of a particular weekday, given the date, is found by dividing by 7 and rounding up.

The ordinal can be added using any of the answers to Add st, nd, rd and th (ordinal) suffix to a number.

E.g.

function nthDate(date = new Date()) {
  let dayname = date.toLocaleString('en', {weekday: 'long'});
  let nth = Math.ceil(date.getDate() / 7);
  nth  = ["st", "nd", "rd"][((nth   90) % 100 - 10) % 10 - 1] || "th";
  return `${nth} ${dayname}`;
}

let d = new Date();
console.log(`Today is the ${nthDate(d)} of ${d.toLocaleString('en',{month:'long', year:'numeric'})}.`);

  • Related