export function generateDateRange(startDate, endDate, granularity) {
const dateRange = [];
let currentDate = new Date(startDate);
while (currentDate <= new Date(endDate)) {
if (granularity === 'daily') {
dateRange.push({ time: currentDate.toISOString().split('T')[0] });
currentDate.setDate(currentDate.getDate() + 1);
} else if (granularity === 'weekly') {
const startOfWeek = new Date(currentDate);
startOfWeek.setDate(currentDate.getDate() - currentDate.getDay());
const endOfWeek = new Date(startOfWeek);
endOfWeek.setDate(endOfWeek.getDate() + 6);
dateRange.push({
time: `${currentDate.getFullYear()}年第${getWeekNumber(currentDate)}周`,
startTime: startOfWeek.toISOString().split('T')[0],
endTime: endOfWeek.toISOString().split('T')[0]
});
currentDate.setDate(currentDate.getDate() + 7);
} else if (granularity === 'monthly') {
dateRange.push({ time: currentDate.toISOString().substring(0, 7) });
currentDate.setMonth(currentDate.getMonth() + 1);
} else if (granularity === 'quarterly') {
const quarter = getQuarter(currentDate);
const year = currentDate.getFullYear();
dateRange.push({ time: `${year}Q${quarter}` });
currentDate.setMonth(currentDate.getMonth() + 3);
} else if (granularity === 'yearly') {
dateRange.push({ time: currentDate.getFullYear().toString() });
currentDate.setFullYear(currentDate.getFullYear() + 1);
}
}
return dateRange;
}
// Helper function to get the week number
export function getWeekNumber(date) {
const onejan = new Date(date.getFullYear(), 0, 1);
return Math.ceil(((date - onejan) / 86400000 + onejan.getDay() + 1) / 7);
}
// Helper function to get the quarter
export function getQuarter(date) {
return Math.ceil((date.getMonth() + 1) / 3);
}
用法如下:
const startDate = '2024-01-01';
const endDate = '2024-01-07';
const dailyRange = generateDateRange(startDate, endDate, 'daily');
console.log(dailyRange);
const weeklyRange = generateDateRange(startDate, endDate, 'weekly');
console.log(weeklyRange);
const monthlyRange = generateDateRange(startDate, endDate, 'monthly');
console.log(monthlyRange);
const quarterlyRange = generateDateRange(startDate, endDate, 'quarterly');
console.log(quarterlyRange);
const yearlyRange = generateDateRange(startDate, endDate, 'yearly');
console.log(yearlyRange);
上述代码将按照日度、周度、月度、季度和年度输出相应的日期范围。
本文介绍了如何使用JavaScript编写一个名为`generateDateRange`的函数,该函数根据给定的开始日期、结束日期和粒度(每日、每周、每月、每季度或每年)生成相应的日期范围对象。
1111

被折叠的 条评论
为什么被折叠?



