由于每个月的天数可能有 28、29、30、31这四种情况,所有最近30天的日期会出现以下三种情况:

  • 开始日期和结束日期都是当前月,同一个月
  • 开始日期是上个月,结束日期是当前月
  • 开始日期是上上个月,中间是 2 月,结束日期是当前月

对日期的处理使用的是 dayjs 模块

npm install --save dayjs

获取当天日期(结束日期)和开始日期

// 开始日期 dayjs 对象
const endDayjs = dayjs();

// 结束日期 dayjs 对象,最近 30 天,包含当前的话,则需要当前日期减去 29 天
const startDayjs = dayjs().subtract(29, 'days');

// dayjs 获取日期的天数、月份、年份的方法,注意获取到的月份比实际小 1,所有需要加上 1

dayjs().year();
dayjs().month() + 1;
dayjs().date();

获取每月共有多少天,计算最近 30 天是否跨月份

dayjs().daysInMonth()

生成指定范围的数组,以下代码表示生成 [1, 2, 3, .... 30],注意不包含结尾的数字。

_.range(1, 31) 

_.each 表示对数组进行循环,类似 for 或 Array map 方法

重点来了,完整代码以下:

const _ = require('lodash');
const dayjs = require('dayjs');

function last30dates()  {
  const endDayjs = dayjs();
  const endYear = endDayjs.year();
  const endMonth = endDayjs.month() + 1;
  const endMonthString = endMonth < 10 ? '0' + endMonth.toString() : endMonth.toString();
  const endDate = endDayjs.date();
  const startDayjs = dayjs().subtract(29, 'days');
  const startYear = startDayjs.year();
  const startMonth = startDayjs.month() + 1;
  const startMonthString = startMonth < 10 ? '0' + startMonth.toString() : startMonth.toString();
  const startDate = startDayjs.date();
  const dates = [];
  if (endMonth === startMonth) {
    // 同一个月,直接改变天数
    _.each(_.range(startDate, endDate + 1), (item) => {
      if (item < 10) {
        item = '0' + item.toString();
      }
      dates.push(`${endYear}-${endMonthString}-${item}`);
    });
  } else if (endMonth === startMonth + 1 || startMonth - endMonth === 11) {
    // 上一个月和当前月
    // 上个月
    _.each(_.range(startDate, startDayjs.daysInMonth() + 1), (item) => {
      if (item < 10) {
        item = '0' + item.toString();
      }
      dates.push(`${startYear}-${startMonthString}-${item}`);
    });

    // 当前月
    _.each(_.range(1, endDate + 1), (item) => {
      if (item < 10) {
        item = '0' + item.toString();
      }
      dates.push(`${endYear}-${endMonthString}-${item}`);
    });
  } else if (endMonth === startMonth + 2) {
    // 上上个月、上个月和当前月,遇到 2 月时
    // 上上个月
    _.each(_.range(startDate, startDayjs.daysInMonth() + 1), (item) => {
      if (item < 10) {
        item = '0' + item.toString();
      }
      dates.push(`${startYear}-${startMonthString}-${item}`);
    });

    // 2 月
    _.each(_.range(1, startDayjs.add(1, 'months').daysInMonth() + 1), (item) => {
      if (item < 10) {
        item = '0' + item.toString();
      }
      dates.push(`${startYear}-02-${item}`);
    });

    // 当前月
    _.each(_.range(1, endDate + 1), (item) => {
      if (item < 10) {
        item = '0' + item.toString();
      }
      dates.push(`${endYear}-${endMonthString}-${item}`);
    });
  }

  return dates;
};

标签: Node.js