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

JS比较两个Date日期显示对应图标时if判断始终失效如何解决

问题根因

  • Date属于引用类型,直接用===比较的是两个对象的内存地址而非日期值,即使两个日期的时间戳完全一致,===判断也会返回false
  • getDay()是获取当前星期(返回值0-6对应周日到周六),要获取当月的日期需要调用getDate()方法
  • new Date(year, monthIndex, day)的月份参数是从0开始计数的,你已经给月份做了+1处理,传入构造函数后会比实际月份多1个月
  • 模板嵌套逻辑错误,currentIcon的判断模板嵌套在pastIcon的判断分支内,即使currentIcon为true,也需要pastIcon同时为true才会生效,不符合互斥的业务逻辑

修复代码

JS逻辑部分

connectedCallback() {
    const today = new Date();
    // 构造当天0点的日期对象,避免时分秒干扰判断
    const currentDate = new Date(today.getFullYear(), today.getMonth(), today.getDate());
    // 构造目标日期0点的对象,月份参数传9对应10月
    const targetDate = new Date(2021, 9, 5);
    // 比较时间戳判断日期是否相等
    if (currentDate.getTime() === targetDate.getTime()) {
        this.currentIcon = true;
        this.pastIcon = false;
    } else {
        this.currentIcon = false;
        this.pastIcon = true;
    }
}

模板部分

<template>
    <template if:true={pastIcon}>
        <lightning-dynamic-icon type="trend" option="down" alternative-text="Trending down">
        </lightning-dynamic-icon>
    </template>
    <template if:true={currentIcon}>
        <lightning-dynamic-icon type="trend" option="up" alternative-text="Trending up">
        </lightning-dynamic-icon>
    </template>
</template>

补充说明

日期比较也可以直接用+操作符转换为时间戳简写:+currentDate === +targetDate,效果和getTime()完全一致。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 06:24:06