迹忆客 专注技术分享

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

在 JavaScript 中从日期中减去小时数

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

从日期中减去小时数:

  1. 使用 getHours() 方法获取特定日期的小时数。
  2. 使用 setHours() 方法设置日期的小时数。
  3. setHours 方法将小时作为参数并设置日期的值。
function subtractHours(numOfHours, date = new Date()) {
  date.setHours(date.getHours() - numOfHours);

  return date;
}

// 👇️ Subtract 1 hour from the current date
const result = subtractHours(1);

// 👇️ Subtract 2 hours from another date
const date = new Date('2022-04-27T08:30:10.820');

// 👇️ Wed Apr 27 2022 06:30:10
console.log(subtractHours(2, date));

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

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

getHours() 方法返回一个介于 0 和 23 之间的数字,该数字根据本地时间表示给定日期的小时。

setHours() 方法将表示小时的数字作为参数并设置日期的值。

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

const date = new Date('2022-04-27T01:30:10.820');

date.setHours(date.getHours() - 3);

console.log(date); // 👉️ Tue Apr 26 2022 22:30:10

在示例中,从日期中减去 3 小时会自动调整月份中的日期。

请注意,setHours 方法会改变调用它的 Date 对象。 如果我们不想就地更改日期,请在调用该方法之前创建一个副本。

function subtractHours(numOfHours, date = new Date()) {
  const dateCopy = new Date(date.getTime());

  dateCopy.setHours(dateCopy.getHours() - numOfHours);

  return dateCopy;
}

const date = new Date('2022-04-27T08:30:10.820');

const result = subtractHours(4, date);

console.log(result); // 👉️ Wed Apr 27 2022 04:30:10

console.log(date); // 👉️ Wed Apr 27 2022 08:30:10 (didn't change original)

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

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

当我们必须在代码的其他位置使用原始 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

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便