迹忆客 专注技术分享

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

在 JavaScript 中从日期中减去周

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

从日期中减去周数:

  1. 使用 getDate() 方法获取特定日期的月份日期。
  2. 使用 setDate() 方法设置日期的月份日期。
  3. setDate 方法将月份中的某天作为参数并设置日期的值。
function subtractWeeks(numOfWeeks, date = new Date()) {
  date.setDate(date.getDate() - numOfWeeks * 7);

  return date;
}

// 👇️ Subtract 1 week from current date
const result = subtractWeeks(1);
console.log(result);

// 👇️ Subtract 2 weeks from another date
// 👇️ Thu Feb 03 2022
console.log(subtractWeeks(2, new Date('2022-02-17')));

我们创建了一个可重用的函数,它获取周数和一个 Date 对象,然后从日期中减去周数。

如果没有为函数提供 Date 对象,则它使用当前日期。

getDate() 方法返回一个介于 1 和 31 之间的整数,表示该日期的月份中的哪一天。

要从一个月中的某天减去几周,我们必须每周减去 7 天。

setDate() 方法将表示月份中的某天的数字作为参数,并设置 Date 上的值。

JavaScript Date 对象自动负责调整月份和年份,如果从日期中减去 X 周会将我们推到上一个月或上一年。

const date = new Date('2022-04-01');

date.setDate(date.getDate() - 4 * 7);

console.log(date); // 👉️ Fri Mar 04 2022

在示例中从自动调整月份的日期减去 4 周。

注意setDate 方法会改变调用它的 Date 对象。 如果不想就地更改日期,可以在调用该方法之前创建它的副本。

function subtractWeeks(numOfWeeks, date = new Date()) {
  const dateCopy = new Date(date.getTime());
  dateCopy.setDate(dateCopy.getDate() - numOfWeeks * 7);

  return dateCopy;
}

const date = new Date('2022-04-27');

const result = subtractWeeks(3, date);

console.log(result); // 👉️ Wed Apr 06 2022

console.log(date); // 👉️ Wed Apr 27 2022

getTime 方法返回从 1970 年 1 月 1 日 00:00:00 到给定日期之间经过的毫秒数。

我们使用时间戳创建了 Date 对象的副本,因此在调用 setDate 方法时我们不会对其进行更改。

当我们必须在代码的其他位置使用原始 Date 对象时,复制日期非常有用。

一般来说,改变函数参数是一种不好的做法,因为多次将相同的参数传递给同一个函数会返回不同的结果。

转载请发邮件至 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

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便