使用 JavaScript 检查日期是否早于今天的日期
要检查日期是否早于今天的日期:
-
使用
Date()
构造函数创建新日期。 - (可选)将日期时间设置为午夜。
- 检查传入的日期是否小于今天的日期。
function isBeforeToday(date) {
const today = new Date();
today.setHours(0, 0, 0, 0);
return date < today;
}
const yesterday = new Date();
yesterday.setDate(yesterday.getDate() - 1);
const tomorrow = new Date();
tomorrow.setDate(tomorrow.getDate() + 1);
console.log(isBeforeToday(yesterday)); // 👉️ true
console.log(isBeforeToday(tomorrow)); // 👉️ false
console.log(isBeforeToday(new Date())); // 👉️ false
我们创建了一个可重用的函数来检查传入的日期是否早于今天的日期。
我们在函数中做的第一件事是使用 Date()
构造函数来获取当前日期。
setHours
方法将小时、分钟、秒和毫秒作为参数并更改给定 Date
实例的值。
在这一行中,我们基本上将今天日期的时间设置为午夜,因此我们检查传入的日期是否为昨天或更早的日期。
如果我们删除使用 setHours()
方法的行,我们将检查日期是否在过去,不一定是昨天或进一步删除。
最后一步是返回检查传入的日期是否小于今天的日期的结果。
我们能够比较日期,因为在引擎盖下每个日期存储一个时间戳 - 1970 年 1 月 1 日 和给定日期之间经过的毫秒数。
const date = new Date('2022-09-24');
// 👇️ 1663977600000
console.log(date.getTime());
每个日期都在后台存储一个时间戳,因此默认行为是比较日期的时间戳,即使我们没有在每个日期上显式调用
getTime()
方法也是如此。
如果传入的日期小于今天的日期,那么它是过去的。
相关文章
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 中合并两个数组,以及如何删除任何重复的数组。