使用 JavaScript 获取上周一的日期
JavaScript 中要获取前一个星期一的日期:
- 将 6 加到星期几,得到除以 7 的余数。
- 从当月的第几天中减去结果。
function getPreviousMonday(date = new Date()) {
const previousMonday = new Date();
previousMonday.setDate(date.getDate() - ((date.getDay() + 6) % 7));
return previousMonday;
}
// 👇️ "Mon Jan 10 2022 15:45:00"
console.log(getPreviousMonday(new Date('2022-01-11')));
// 👇️ "Mon Jan 03 2022 15:45:00"
console.log(getPreviousMonday(new Date('2022-01-09')));
我们创建了一个可重用的函数,它将 Date
对象作为参数并返回前一个星期一。
如果未提供参数,则该函数返回当前日期的前一个星期一。
setDate
方法允许我们更改特定 Date 实例的月份日期。
该方法采用一个整数来表示一个月中的第几天。
为了回到上周一,我们:
-
将 6 添加到星期几,例如 星期二 =
2 + 6 = 8
。请注意,getDay() 方法返回星期日为 0、星期一为 1、星期二为 2 等的星期几。 - 使用模运算符得到除以 8 % 7 = 1 的余数。
- getDate() 方法返回一个月中的第几天,例如 11 - 1 = 10。
- 10 是前一个星期一所在月份的第几天。
请注意
,setDate
方法会在适当的位置改变 Date 对象,更改它的日期值。
我们创建了一个新的 Date() 对象并将其存储在 previousMonday 变量中以避免改变传入的 Date。
请注意,如果向函数传递的日期已经是星期一,它将按原样返回日期。
例如 2022-01-10
是星期一。
-
将 6 添加到凌晨的日期,例如 星期一 =
1 + 6 = 7
。 - 得到余数 - 7 % 7 = 0。
- 并从该月的第几天中减去结果 - 10 - 0 = 10。
- 该方法返回一个存储同一星期一的新日期。
如果想重新设置Date的时间,将时、分、秒、毫秒设置为0,可以使用 setHours()
方法。
function getPreviousMonday(date = new Date()) {
const previousMonday = new Date();
previousMonday.setDate(date.getDate() - ((date.getDay() + 6) % 7));
// 👇️ Reset hours, minutes, seconds, milliseconds to `0`
previousMonday.setHours(0, 0, 0, 0);
return previousMonday;
}
// 👇️ "Mon Jan 10 2022 00:00:00"
console.log(getPreviousMonday(new Date('2022-01-12')));
我们传递给 setHours
方法的四个参数是小时、分钟、秒和毫秒。
这会将返回日期的时间重置为午夜。
相关文章
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 中合并两个数组,以及如何删除任何重复的数组。