简体   繁体   中英

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.

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

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM