碎片时间学编程「297]:以字符串表示形式计算从今天算起的几天前的日期

使用Date构造函数获取当前日期。
使用Math.abs()和 Date.prototype.getDate()方法相应地更新日期并使用 Date.prototype.setDate() 设置为结果。
使用Date.prototype.toISOString()以格式返回字符串yyyy-mm-dd。
JavaScript
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)
更多内容请访问我的网站:https://www.icoderoad.com