在 JavaScript 中检查两个日期是否是同一天
JavaScript 中检查两个日期是否是同一天:
-
比较两个日期的
getFullYear()
方法的输出。 -
对
getMonth()
和getDate()
方法的输出执行相同的操作。 - 如果满足条件,则日期为同一天。
const date1 = new Date('2022-06-19');
const date2 = new Date('2022-06-19');
if (
date1.getFullYear() === date2.getFullYear() &&
date1.getMonth() === date2.getMonth() &&
date1.getDate() === date2.getDate()
) {
console.log('✅ dates are the same day');
} else {
console.log('⛔️ dates are not the same day');
}
我们使用了以下 3 种与日期相关的方法:
- Date.getFullYear 方法 - 返回代表与日期对应的年份的四位数字。
-
Date.getMonth - 返回一个介于 0(一月)和 11(十二月)之间的整数,代表给定日期的月份。 不幸的是,
getMonth
方法偏移了 1。 - Date.getDate - 返回一个介于 1 和 31 之间的整数,表示特定日期的月份中的第几天。
我们使用了逻辑与 &&
运算符,这意味着要运行我们的 if 块,必须满足所有条件。
const date1 = new Date('2022-06-19');
const date2 = new Date('2022-06-19');
if (
date1.getFullYear() === date2.getFullYear() &&
date1.getMonth() === date2.getMonth() &&
date1.getDate() === date2.getDate()
) {
console.log('✅ dates are the same day');
} else {
console.log('⛔️ dates are not the same day');
}
如果日期具有相同的年月日,则它们是同一天。
或者,我们可以使用 toDateString
方法。
要检查两个日期是否是同一天,请对两个 Date()
对象调用 toDateString()
方法并比较结果。 如果调用该方法的输出相同,则日期是同一天。
const date1 = new Date('2022-06-19');
const date2 = new Date('2022-06-29');
if (date1.toDateString() === date2.toDateString()) {
console.log('✅ dates are the same day');
} else {
console.log('⛔️ dates are not the same day');
}
toDateString()
方法返回一个字符串,该字符串以人类可读的形式表示给定 Date 对象的日期部分。
const date1 = new Date('2022-06-19');
// 👇️ Sun Jun 19 2022
console.log(date1.toDateString());
如果对两个 Date
对象调用该方法返回两个相等的字符串,则日期是同一天。
相关文章
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 中合并两个数组,以及如何删除任何重复的数组。