JS 判断日期是否大于当前日期

在前端开发中,经常会遇到需要判断一个日期是否大于当前日期的情况。这个需求可能会出现在预约功能、倒计时功能等场景中。在 JavaScript 中,我们可以通过一些简单的方法来实现这个功能。
1. 获取当前日期
首先,我们需要获取当前日期,以便与给定日期进行比较。在 JavaScript 中,可以使用 new Date() 方法来获取当前日期。示例代码如下:
const currentDate = new Date();
console.log(currentDate);
运行上述代码,可以得到当前日期的字符串表示,例如:Mon Nov 01 2021 10:00:00 GMT+0800 (中国标准时间)。
2. 将字符串日期转换为 Date 对象
接下来,我们需要将给定的日期字符串转换为 Date 对象,以便进行比较。示例代码如下:
const dateString = '2021-11-15';
const givenDate = new Date(dateString);
console.log(givenDate);
上述代码中,我们将字符串 '2021-11-15' 转换为 Date 对象,并打印出来。
3. 比较日期
有了当前日期和给定日期的 Date 对象,我们可以通过比较它们的时间戳来判断日期的大小关系。示例代码如下:
if (currentDate.getTime() < givenDate.getTime()) {
console.log('给定日期大于当前日期');
} else if (currentDate.getTime() > givenDate.getTime()) {
console.log('给定日期小于当前日期');
} else {
console.log('给定日期等于当前日期');
}
运行上述代码,根据给定日期与当前日期的大小关系,会打印出相应的结果。
4. 完整示例
下面是一个完整的示例,包括获取当前日期、将字符串日期转换为 Date 对象、比较日期的部分:
const currentDate = new Date();
const dateString = '2021-11-15';
const givenDate = new Date(dateString);
if (currentDate.getTime() < givenDate.getTime()) {
console.log('给定日期大于当前日期');
} else if (currentDate.getTime() > givenDate.getTime()) {
console.log('给定日期小于当前日期');
} else {
console.log('给定日期等于当前日期');
}
在这个示例中,我们首先获取当前日期,然后将字符串日期 '2021-11-15' 转换为 Date 对象,最后比较两个日期的时间戳,输出判断结果。
极客笔记