← 输入框|github.com|刷新
Skip to content

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

Open

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

Activity

  1. liwenkang commented on May 13, 2019

    @liwenkang
    /**
     * 获取当前时间 n天前的毫秒数
     * @param n
     * @returns {number}
     */
    function getPastDay(n) {
        return Date.now() - (n * 86400000);
    }
    
    /**
     * 月/日不够两位的补 0
     * @param num
     * @returns {string|*}
     */
    function padStart(num) {
        if (num < 10) {
            return '0' + num;
        }
        return num;
    }
    
    /**
     * @param time 是要转换的时间(以毫秒为单位)
     * @returns {string}
     */
    function formatTime(time) {
        const date = new Date(time);
        const year = date.getFullYear();
        const month = padStart(date.getMonth() + 1);
        const day = padStart(date.getDate());
        return `${year}-${month}-${day}`;
    }
    
    /**
     * @param {number} n - 天数
     * @return {Array} 日期数组,格式:[yyyy-MM-dd, yyyy-MM-dd]
     */
    function getPastDays(n) {
        let result = [];
        while (n > 0) {
            result.push(formatTime(getPastDay(n--)));
        }
        return result;
    }
  2. Wxh16144 commented on May 14, 2019

    @Wxh16144

    早上上班看到这个题目,想到了微信公众号前端早读课推送的一篇文章【第1608期】What's New in JavaScript(视频)

    参考MDN Intl.DateTimeFormat
    参考Can I use

    /**
     * @param {number} n - 天数
     * @return {array} 日期数组,格式:[yyyy-MM-dd, yyyy-MM-dd]
     */
    const getPastDays = n => {
      return [...Array(n || 7).keys()].map(days => {
        const date = new Date(Date.now() - 86400000 * ( days + 1 ))
        return new Intl.DateTimeFormat('zh', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit'
        }).format(date)
          .replace(/\//g, '-')
      })
    }
    console.log(getPastDays(7)); 
    // ["2019-05-13", "2019-05-12", "2019-05-11", "2019-05-10", "2019-05-09", "2019-05-08", "2019-05-07"]
  3. wingmeng commented on May 14, 2019

    @wingmeng
    CollaboratorAuthor

    早上上班看到这个题目,想到了微信公众号前端早读课推送的一篇文章【第1608期】What's New in JavaScript(视频)

    参考MDN Intl.DateTimeFormat
    参考Can I use

    /**
     * @param {number} n - 天数
     * @return {array} 日期数组,格式:[yyyy-MM-dd, yyyy-MM-dd]
     */
    const getPastDays = n => {
      return [...Array(n || 7).keys()].map(days => {
        const date = new Date(Date.now() - 86400000 * ( days + 1 ))
        return new Intl.DateTimeFormat('zh', {
          year: 'numeric',
          month: '2-digit',
          day: '2-digit'
        }).format(date)
          .replace(/\//g, '-')
      })
    }
    console.log(getPastDays(7)); 
    // ["2019-05-13", "2019-05-12", "2019-05-11", "2019-05-10", "2019-05-09", "2019-05-08", "2019-05-07"]

    答案非常精彩,然而返回的日期顺序应该是从远到近。

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

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