欢迎光临散文网 会员登陆 & 注册

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

2023-04-05 18:10 作者:路条编程  | 我要投稿



  • 使用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


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

分享到微博请遵守国家法律