📅  最后修改于: 2023-12-03 15:23:10.417000             🧑  作者: Mango
在 JavaScript 中获取上一周的日期可以使用 Date 对象的方法和一些简单的计算来完成。以下是实现方法:
new Date()
构造函数来获取。let currentDate = new Date();
let oneWeekMs = 7 * 24 * 60 * 60 * 1000;
let lastWeekDateMs = currentDate.getTime() - oneWeekMs;
let lastWeekDate = new Date(lastWeekDateMs);
let lastWeekYear = lastWeekDate.getFullYear();
let lastWeekMonth = lastWeekDate.getMonth() + 1;
let lastWeekDay = lastWeekDate.getDate();
完整代码如下:
let currentDate = new Date();
let oneWeekMs = 7 * 24 * 60 * 60 * 1000;
let lastWeekDateMs = currentDate.getTime() - oneWeekMs;
let lastWeekDate = new Date(lastWeekDateMs);
let lastWeekYear = lastWeekDate.getFullYear();
let lastWeekMonth = lastWeekDate.getMonth() + 1;
let lastWeekDay = lastWeekDate.getDate();
console.log(`上一周的日期为:${lastWeekYear}-${lastWeekMonth}-${lastWeekDay}`);
输出结果为:
上一周的日期为:2021-1-17
以上就是在 JavaScript 中获取上一周日期的方法。