在 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 对象调用该方法返回两个相等的字符串,则日期是同一天。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。