javascriptdatedayofmonth

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


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.


Solution

  • 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())