使用 JavaScript 获取上周的日期
要获取上周的日期,请使用 Date()
构造函数创建一个新日期,并将年、月和当前月的日期减去 7 传递给它从而获取当前日期的前一周的日期。
function getLastWeeksDate() {
const now = new Date();
return new Date(now.getFullYear(), now.getMonth(), now.getDate() - 7);
}
// 👇️ Sun Jan 09 2022 00:00:00
console.log(getLastWeeksDate());
// 👇️ Sun Jan 16 2022 15:26:30
console.log(new Date());
我们使用了以下 3 种与日期相关的方法:
- Date.getFullYear 方法 - 返回一个四位数字,表示对应于日期的年份。
- Date.getMonth - 返回一个介于 0(一月)和 11(十二月)之间的整数,表示给定日期的月份。 是的,不幸的是 getMonth 方法关闭了 1。
- Date.getDate - 返回一个介于 1 到 31 之间的整数,表示特定日期的月份日期。
通过从当前日期减去 7 天,我们得到上周的日期。
JavaScript 中的
Date()
对象会自动滚动或返回,如果月份中的天数为负数,则会调整月份和/或年份。
如果要保留时间,可以将 1 周转换为毫秒,然后从当前日期的毫秒中减去结果。
function getLastWeeksDate() {
const now = new Date();
return new Date(now.getTime() - 7 * 24 * 60 * 60 * 1000);
}
// 👇️ Sun Jan 09 2022 15:34:30
console.log(getLastWeeksDate());
// 👇️ Sun Jan 16 2022 15:34:30
console.log(new Date());
getTime
方法返回自特定日期的 unix 纪元以来的毫秒数。
通过从值中减去一周的毫秒数,我们得到上周的日期并保留时间分量。
我们还可以将 Date
对象作为函数中的参数来获取任何 Date 的前一周的日期。
相关文章
Do you understand JavaScript closures?
发布时间:2025/02/21 浏览次数:108 分类:JavaScript
-
The function of a closure can be inferred from its name, suggesting that it is related to the concept of scope. A closure itself is a core concept in JavaScript, and being a core concept, it is naturally also a difficult one.
Do you know about the hidden traps in variables in JavaScript?
发布时间:2025/02/21 浏览次数:178 分类:JavaScript
-
Whether you're just starting to learn JavaScript or have been using it for a long time, I believe you'll encounter some traps related to JavaScript variable scope. The goal is to identify these traps before you fall into them, in order to av
How much do you know about the Prototype Chain?
发布时间:2025/02/21 浏览次数:150 分类:JavaScript
-
The prototype chain can be considered one of the core features of JavaScript, and certainly one of its more challenging aspects. If you've learned other object-oriented programming languages, you may find it somewhat confusing when you start
如何在 JavaScript 中合并两个数组而不出现重复的情况
发布时间:2024/03/23 浏览次数:86 分类:JavaScript
-
本教程介绍了如何在 JavaScript 中合并两个数组,以及如何删除任何重复的数组。