How do I get the first upcoming thursday in everymonth in javascript?

888 views Asked by At

What I want to do is get the date of today and then find the first Thursday of the month, if that day has already passed in this month then get the date of the first Thursday of the next month.

I'll provide an example due to me being a bit vague. Let us say that the first Thursday of the month is on the 2nd of May and its the 1st of may right now. In that case, I would want to get the date of that Thursday due to it being the upcoming one. But let's say it was the 13th of May and that date has already past then I would like to get the date of the next first Thursday of the coming month.

2

There are 2 answers

0
mplungjan On BEST ANSWER

Try this

const firstThur = d => {
  const firstThur = new Date(d.getFullYear(),d.getMonth(),1,15,0,0,0); // first of the month
  for (let i=1;i<7;i++) {
    if (firstThur.getDay() === 4) break;
    firstThur.setDate(firstThur.getDate()+1)
  }
  return firstThur;
};  


const getThursday = () => {
  const now = new Date();
  now.setHours(15,0,0,0); // normalise
  let ft = firstThur(now);
  return now.getTime() <= ft.getDate ? ft : firstThur(new Date(now.getFullYear(),now.getMonth()+1,1,15,0,0,0))
}; 
console.log(getThursday())

0
RobG On

You can create a date for the first of the month, then move it to the first Thursday. Test it against the passed in date and if it's earlier, get the first Thursday for the following month.

The following assumes that if the passed in date is the first Thursday, that Thursday should be returned. It also assumes that the passed in date has its hours zeroed, otherwise if it's the first Thursday it will return the first in the following month.

It also just sets the date to the first Thursday, so no looping to find the day.

function getFirstThursday(date = new Date()) {
  // Create date for first of month
  let d = new Date(date.getFullYear(), date.getMonth());
  // Set to first Thursday
  d.setDate((12 - d.getDay()) % 7);
  // If before date, get first Thursday of next month
  if (d < date) {
    d.setMonth(d.getMonth() + 1, 1);
    return getFirstThursday(d);
  } else {
    return d;
  }
}

// Some tests
let f = d => d.toLocaleString('en-gb', {
  day:'2-digit',weekday:'short',month:'short'
});
[new Date(2020,8, 1), //  1 Sep -> 3 Sep
 new Date(2020,8, 2), //  2 Sep -> 3 Sep
 new Date(2020,8, 3), //  3 Sep -> 3 Sep
 new Date(2020,8,24), // 24 Sep -> 1 Oct
 new Date(2020,9, 1), //  1 Oct -> 1 Oct
 new Date(2020,9, 2), //  2 Oct -> 5 Nov
 new Date(2020,9,26), // 26 Oct -> 5 Nov
 new Date(2020,9,27)  // 27 Oct -> 5 Nov
 ].forEach( d => console.log(
   `${f(d)} => ${f(getFirstThursday(d))}`
 ));

The else block is redundant, the second return could just follow the if but it makes things clearer I think.