n
以字符串表示形式计算从今天开始的几天前的日期。
- 使用
Date
构造函数获取当前日期。 - 使用
Math.abs()
和Date.prototype.getDate()
相应地更新日期并使用 设置为结果Date.prototype.setDate()
。 - 用于
Date.prototype.toISOString()
以yyyy-mm-dd
格式返回字符串。
const daysAgo = n => {
let d = new Date();
d.setDate(d.getDate() - Math.abs(n));
return d.toISOString().split('T')[0];
};
daysAgo(20); // 2020-09-16 (if current date is 2020-10-06)