Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
wingmeng opened this issue May 13, 2019 · 3 comments
Open

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

wingmeng opened this issue May 13, 2019 · 3 comments

Comments

@wingmeng
Copy link
Collaborator

wingmeng commented May 13, 2019

来源:原创题
难度:★★

封装一个函数,接收一个整数参数 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

@liwenkang
Copy link

/**
 * 获取当前时间 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;
}

@Wxh16144
Copy link

Wxh16144 commented May 14, 2019

早上上班看到这个题目,想到了微信公众号前端早读课推送的一篇文章【第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"]

@wingmeng
Copy link
Collaborator Author

早上上班看到这个题目,想到了微信公众号前端早读课推送的一篇文章【第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
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants