使用 JavaScript 将日期四舍五入到最近的小时
JavaScript 将日期四舍五入到最接近的小时:
-
使用
setMinutes()
方法将日期的分钟数设置为其当前分钟数 + 30。 -
使用
setMinutes()
方法将分、秒和毫秒设置为 0。 - 如果在日期上加上 30 分钟会转到下一个小时,则将小时向上取整,否则向下取整。
function roundToNearestHour(date) {
date.setMinutes(date.getMinutes() + 30);
date.setMinutes(0, 0, 0);
return date;
}
// 👇️ Sun Jan 16 2022 14:00:00 (minutes are 30)
console.log(roundToNearestHour(new Date(2022, 0, 16, 13, 30, 00)));
// 👇️ Sun Jan 16 2022 13:00:00 (minutes are 29)
console.log(roundToNearestHour(new Date(2022, 0, 16, 13, 29, 00)));
在将示例记录到控制台时,我们使用了 Date()
构造函数。我们传递的参数是:year
、month
(January = 0、February = 1 等)、day of month
、hours
、minutes
、seconds
。
我们创建了一个可重用的函数,将日期和时间四舍五入到最接近的小时。
setMinutes
方法设置日期对象的分钟数。
该方法采用以下 3 个参数:
-
minutesValue
- 0 到 59 之间的整数,表示分钟。 -
secondsValue
(可选)- 0 到 59 之间的整数,表示秒。 -
msValue
(可选)- 一个介于 0 和 999 之间的数字,表示毫秒。
在我们第一次调用 setMinutes()
方法时,我们使用 getMinutes()
方法获取日期对象的分钟数,并将结果加 30。
如果在当前时间上加 30 分钟会使小时值增加 1,那么我们应该四舍五入到下一个最接近的小时。
另一方面,如果将时间增加 30 分钟不会增加小时,则时间为 29 分钟或更短,我们应该将分钟数向下舍入为 0。
JavaScript 中的 Date 对象会自动处理将日期和时间增加 30 分钟会滚动到下一个小时甚至可能是第二天的情况。
function roundToNearestHour(date) {
date.setMinutes(date.getMinutes() + 30);
date.setMinutes(0, 0, 0);
return date;
}
// 👇️ Sun Jan 17 2022 00:00:00 (minutes are 30)
console.log(roundToNearestHour(new Date(2022, 0, 16, 23, 30, 00)));
在上面的示例中,我们将小时四舍五入,并且
Date()
对象会自动滚动到第二天,因为将小时四舍五入会更改日期。
在我们第二次调用 setMinutes()
方法时,我们将分、秒和毫秒设置为 0,以确保日期和时间对象指向整点,例如 08:00:00,而不是 08:00:30。
相关文章
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 中合并两个数组,以及如何删除任何重复的数组。