js根据开始结束时间 获取对应区间内的时间,按照年、季、月、周、日

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);
上述代码将按照日度、周度、月度、季度和年度输出相应的日期范围。

  • 7
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值