Skip to content

第 6 期(2019-05-13):获取过去n天的日期 #8

@wingmeng

Description

@wingmeng

来源:原创题
难度:★★

封装一个函数,接收一个整数参数 n ,返回当天前 n 天的日期(不含当天)

/**
 * @param {number} n - 天数
 * @return {array} 日期数组,格式:[yyyy-MM-dd, yyyy-MM-dd]
 */
function getPastDays(n) {
  // 你的代码
}

测试用例:

getPastDays(7);  // 获取前 7 天的日期(今天是:2019年5月13日)

// 运行返回数据:
["2019-05-06", "2019-05-07", "2019-05-08", "2019-05-09", "2019-05-10", "2019-05-11", "2019-05-12"]

参考答案:

function getPastDays(n) {
  // 非整数或负数,返回空数组
  if (!Number.isInteger(n) || n < 0) {
    return [];
  }

  const oneDay = 24 * 3600 * 1e3;  // 将1天时间换算成UTC毫秒数
  const preZero = num => num < 10 ? `0${num}` : num;  // 1位数前置补零

  return (
    [...Array(n).keys()]
      .map(days => new Date(Date.now() - oneDay * (days + 1)))
      .map(day => `${day.getFullYear()}-${preZero(day.getMonth() + 1)}-${preZero(day.getDate())}`)
      .reverse()  // 反转数组,按从远到近的日期顺序
  );
}

本期优秀回答者: @liwenkang @Wxh16144

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions