我需要為以下要求創建一個 JavaScript 函式。我需要獲取每個作業日的日期串列。如果你知道 nodeJs 包,請告訴我。感謝您的關注。
Example -
2022-01-03
2022-01-04
2022-01-05
2022-01-06
2022-01-07
2022-01-10
2022-01-11
2022-01-12
2022-01-13
2022-01-14
..........
..........
until year-end
喜歡這種模式(僅限周一至周五)
uj5u.com熱心網友回復:
function getWeekDaysForYear(year) {
const isLeap = year % 4 === 0;
const numberOfDays = isLeap ? 366 : 365;
let currentDate = new Date(Date.UTC(year, 0, 0, 0, 0, 0, 0));
const weekDays = [];
for(let i = 1; i <= numberOfDays; i ) {
currentDate = new Date(currentDate.getTime() 24 * 3600 * 1000);
if (currentDate.getDay() === 0 || currentDate.getDay() === 6) {
continue;
}
weekDays.push(currentDate.toISOString().split('T')[0]);
}
return weekDays;
}
console.log(getWeekDaysForYear(2022));
這是一個簡單的函式,它回傳陣列中指定年份的所有作業日。
uj5u.com熱心網友回復:
JavaScript 的Date物件溢位,所以你可以使用:
for (i=1;i<366;i ) {
if (i%7==1 || i%7==2) continue;
const d = new Date(2022, 0, i);
document.write(d.toDateString(),'<br>');
}
您需要注意閏年,并重新計算每年的周末。
uj5u.com熱心網友回復:
像這樣的東西
const endDate = new Date(2022,1,2);
const date = new Date(); //today
while (endDate > date) {
const weekDay = date.getDay();
if (weekDay != 6 && weekDay != 0) {
let year = new Intl.DateTimeFormat('en', { year: 'numeric' }).format(date);
let month = new Intl.DateTimeFormat('en', { month: '2-digit' }).format(date);
let day = new Intl.DateTimeFormat('en', { day: '2-digit' }).format(date);
console.log(`${year}-${month}-${day}`);
}
date.setDate(date.getDate() 1);
}
uj5u.com熱心網友回復:
因為我們在打代碼高爾夫……
function getWeekDays(year) {
// Start on 1 Jan of given year
let d = new Date(Date.UTC(year, 0));
let result = [];
do {
// Only push dates that aren't Sat (6) or Sun (0)
d.getDay() % 6 ? result.push(d.toLocaleDateString('en-CA')) : null;
// Increment date
d.setDate(d.getDate() 1);
// Until get to 1 Jan again
} while (d.getMonth() d.getDate() > 1)
return result;
}
console.log(getWeekDays(new Date().getFullYear()))
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/414501.html
標籤:
上一篇:在R中將字串轉換為日期格式
