You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

JavaScript中如何将API返回的本地日期与当前日期比较

统一日期格式完成比较的方法

你直接用new Date(this.date) == new Date()无效的原因是:前者生成的是对应日期00:00:00的时间对象,后者是包含当前时分秒毫秒的时间对象,时间部分不一致导致比较失败。可以用以下两种方法统一格式:

方法一:统一转为当天0点的时间戳

通过setHours(0,0,0,0)清除时分秒毫秒,再比较时间戳:

// 处理API返回的日期,转为当天0点的时间戳
const apiTimestamp = new Date(this.date).setHours(0, 0, 0, 0);
// 处理当前日期,同样转为当天0点的时间戳
const currentTimestamp = new Date().setHours(0, 0, 0, 0);

if (apiTimestamp === currentTimestamp) {
  // 日期相同的逻辑
}

方法二:逐一比较年月日

分别提取两个日期的年、月、日属性进行比对:

const apiDate = new Date(this.date);
const now = new Date();

const sameYear = apiDate.getFullYear() === now.getFullYear();
const sameMonth = apiDate.getMonth() === now.getMonth();
const sameDay = apiDate.getDate() === now.getDate();

if (sameYear && sameMonth && sameDay) {
  // 日期相同的逻辑
}

内容的提问来源于stack exchange,提问作者user3653474

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.16 15:34:57