迹忆客 专注技术分享

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

使用 JavaScript 检查一个日期是否在另一个日期之前

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

要检查一个日期是否早于另一个日期,请比较 Date 对象,例如 date1 < date2。 如果比较返回 true,则第一个日期在第二个日期之前,否则第一个日期等于或在第二个日期之后。

function isBefore(date1, date2) {
  return date1 < date2;
}

const d1 = new Date('2022-02-24');
const d2 = new Date('2022-09-11');

console.log(isBefore(d1, d2)); // 👉️ true

console.log(isBefore(d2, d1)); // 👉️ false

我们创建了一个可重用的函数,它将 2 个 Date 对象作为参数并检查第一个日期是否早于第二个。

如果我们有日期字符串并需要创建 Date 对象,请将日期字符串传递给 Date() 构造函数。

我们能够比较日期,因为在引擎盖下每个日期存储一个时间戳 - 1970 年 1 月 1 日 和给定日期之间经过的毫秒数。

const date = new Date('2022-09-24');

// 👇️ 1663977600000
console.log(date.getTime());

每个日期都在后台存储一个时间戳,因此默认行为是比较日期的时间戳,即使我们没有在每个日期上显式调用 getTime() 方法也是如此。

如果比较返回真,则第二个日期的时间戳大于或等于第一个日期的时间戳。

如果日期的时间戳更大,则自 Unix 纪元以来已经过去了更多时间。

如果两个日期的时间戳相等,则这两个日期的年、月、日、时、分、秒和毫秒值相等。

如果我们在从日期字符串创建有效的 Date 对象时遇到困难,我们可以将 2 种类型的参数传递给 Date() 构造函数:

  1. 一个有效的 ISO 8601 字符串,格式为 YYYY-MM-DDTHH:mm:ss.sssZ,或者只是 YYYY-MM-DD,如果你只有一个没有时间的日期。
  2. 多个逗号分隔的参数,表示年、月(0 = 一月 到 11 = 十二月)、月中的日期、小时、分钟和秒。

下面是一个拆分字符串并将参数传递给 Date() 构造函数以创建 Date 对象的示例。

// 👇️ Formatted as MM/DD/YYYY
const dateStr = '08/24/2022';

const [month, day, year] = dateStr.split('/');

// 👇️ Create valid Date object
const date = new Date(+year, month - 1, +day);
console.log(date); // 👉️ Wed Aug 24 2022

日期字符串的格式为 mm/dd/yyyy,但该方法适用于任何其他格式。

请注意 ,我们在将月份传递给 Date() 构造函数时从月份中减去 1。

这是因为,Date 构造函数需要一个从零开始的值,其中 January = 0、February = 1、March = 2 等。

我们在每个正斜杠上拆分字符串以获得子字符串数组。

const str = '08/24/2022';

// 👇️ ['08', '24', '2022']
console.log(str.split('/'))

我们使用数组解构将月、日和年值分配给变量,并将它们传递给 Date() 构造函数。

从日期字符串创建 Date 对象后,我们可以通过比较它们来检查一个日期是否在另一个日期之前,就像在 JavaScript 中比较数字一样。

转载请发邮件至 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

最新推荐

教程更新

热门标签

扫码一下
查看教程更方便