迹忆客 专注技术分享

当前位置:主页 > 学无止境 > WEB前端 > JavaScript >

使用 JavaScript 获取上周一的日期

作者:迹忆客 最近更新:2022/12/22 浏览次数:

JavaScript 中要获取前一个星期一的日期:

  1. 将 6 加到星期几,得到除以 7 的余数。
  2. 从当月的第几天中减去结果。
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')));

JavaScript 获取上周一的日期

我们创建了一个可重用的函数,它将 Date 对象作为参数并返回前一个星期一。

如果未提供参数,则该函数返回当前日期的前一个星期一。

setDate 方法允许我们更改特定 Date 实例的月份日期。

该方法采用一个整数来表示一个月中的第几天。

为了回到上周一,我们:

  1. 将 6 添加到星期几,例如 星期二 = 2 + 6 = 8。请注意,getDay() 方法返回星期日为 0、星期一为 1、星期二为 2 等的星期几。
  2. 使用模运算符得到除以 8 % 7 = 1 的余数。
  3. getDate() 方法返回一个月中的第几天,例如 11 - 1 = 10。
  4. 10 是前一个星期一所在月份的第几天。

请注意setDate 方法会在适当的位置改变 Date 对象,更改它的日期值。

我们创建了一个新的 Date() 对象并将其存储在 previousMonday 变量中以避免改变传入的 Date。

请注意,如果向函数传递的日期已经是星期一,它将按原样返回日期。

例如 2022-01-10 是星期一。

  1. 将 6 添加到凌晨的日期,例如 星期一 = 1 + 6 = 7
  2. 得到余数 - 7 % 7 = 0。
  3. 并从该月的第几天中减去结果 - 10 - 0 = 10。
  4. 该方法返回一个存储同一星期一的新日期。

如果想重新设置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 方法的四个参数是小时、分钟、秒和毫秒。

这会将返回日期的时间重置为午夜。

转载请发邮件至 1244347461@qq.com 进行申请,经作者同意之后,转载请以链接形式注明出处

本文地址:

相关文章

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 POST

发布时间:2024/03/23 浏览次数:96 分类:JavaScript

本教程讲解如何在不使用 JavaScript 表单的情况下发送 POST 数据。

扫一扫阅读全部技术教程

社交账号
  • https://www.github.com/onmpw
  • qq:1244347461

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便