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

如何在JavaScript中正确比较ISO日期?时分比较结果异常

问题分析与解决

核心问题:重复的判断逻辑

你的isFromBiggerThanTo函数里,from > to和to < from是完全等价的条件——只要from大于to,第一个if分支就会触发返回"blue",剩下的情况只有from <= to,所以第二个else if分支永远不会被执行,自然永远返回不了"red"。

修正后的代码

调整判断逻辑,明确区分「过期」和「未过期」的场景:

function ConvertDateNowToISODate() {    
    // 直接获取当前时间戳,无需多余的ISO转换步骤
    return new Date().getTime();       
}   

function ConvertToExpirationDateToISODate(expirationDate) {
    // 直接将ISO日期转为时间戳,不用先转ISO再转回Date
    return new Date(expirationDate).getTime();
}

function isFromBiggerThanTo(dtmfrom) {
    var from = ConvertToExpirationDateToISODate(dtmfrom);
    var to = ConvertDateNowToISODate();
   
    if (from > to) {
        // 过期时间晚于当前时间,未过期
        return "blue";
    } else if (from < to) {
        // 过期时间早于当前时间,已过期
        return "red";
    } else {
        return "grey";
    }
}

额外优化:简化代码

其实可以直接去掉冗余的转换函数,让逻辑更简洁:

function isFromBiggerThanTo(dtmfrom) {
    const fromTimestamp = new Date(dtmfrom).getTime();
    const nowTimestamp = new Date().getTime();
   
    if (fromTimestamp > nowTimestamp) return "blue";
    if (fromTimestamp < nowTimestamp) return "red";
    return "grey";
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.23 00:24:25