迹忆客 专注技术分享

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

在 JavaScript 中检查两个日期是否是同一天

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

JavaScript 中检查两个日期是否是同一天:

  1. 比较两个日期的 getFullYear() 方法的输出。
  2. getMonth()getDate() 方法的输出执行相同的操作。
  3. 如果满足条件,则日期为同一天。
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');
}

JavaScript 中检查两个日期是否是同一天

我们使用了以下 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');
}

Javascript 使用了逻辑与运算符检查日期

如果日期具有相同的年月日,则它们是同一天。

或者,我们可以使用 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');
}

JavaScript 两个日期不相同

toDateString() 方法返回一个字符串,该字符串以人类可读的形式表示给定 Date 对象的日期部分。

const date1 = new Date('2022-06-19');

// 👇️ Sun Jun 19 2022
console.log(date1.toDateString());

如果对两个 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

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便