簡體   English   中英

如何在javascript中獲得每個月第一個即將到來的星期四?

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

我想要做的是獲取今天的日期,然后找到該月的第一個星期四,如果該日期在本月已經過去,則獲取下個月的第一個星期四的日期。

由於我有點含糊,我將提供一個示例。 假設本月的第一個星期四是 5 月 2 日,現在是 5 月 1 日。 在這種情況下,我想知道那個星期四的日期,因為它是即將到來的日期。 但是假設是 5 月 13 日,那個日期已經過去了,那么我想知道下個月的第一個星期四的日期。

嘗試這個

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

您可以為每月的第一天創建一個日期,然后將其移至第一個星期四。 根據傳遞的日期對其進行測試,如果它更早,則獲取下個月的第一個星期四。

以下假設如果傳入的日期是第一個星期四,則應返回該星期四。 它還假設傳入的日期將其小時數歸零,否則如果是第一個星期四,它將在下個月返回第一個。

它還只是將日期設置為第一個星期四,因此無需循環查找日期。

 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))}` ));

else塊是多余的,第二個返回可以跟在if 之后,但我認為它使事情變得更清晰。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM