-
Notifications
You must be signed in to change notification settings - Fork 6
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
Comments
/**
* 获取当前时间 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;
} |
早上上班看到这个题目,想到了微信公众号 /**
* @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
封装一个函数,接收一个整数参数
n
,返回当天前 n 天的日期(不含当天)测试用例:
参考答案:
本期优秀回答者: @liwenkang @Wxh16144
The text was updated successfully, but these errors were encountered: