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

JavaScript日期时间判断异常:时段判断逻辑错误求助

问题排查与修复方案

Got it, let's fix this time-checking issue for you! The core problem in your code is a typo in the comparison operator—you used arrow function syntax => instead of the greater-than-or-equal-to operator >=, which made your first condition always evaluate to true no matter what time it is.

修正后的完整代码

var inputDate = new Date("5/17/2018"); 
var todaysDate = new Date(); 

// 统一清除时间部分,只比较日期
if(inputDate.setHours(0,0,0,0) === todaysDate.setHours(0,0,0,0)) { 
    // 只创建一次Date实例,避免重复初始化
    var now = new Date();
    var hour = now.getHours(); 
    // 如果Wikitude限制console输出,可以换成alert(hour)临时调试
    console.log("Current hour: " + hour); 

    // 这里把错误的=>改成正确的>=
    if(hour >= 7 && hour < 12) { 
        // 上午页面逻辑
        console.log("Displaying morning page");
    } else if(hour >= 12 && hour <= 18) { 
        // 下午页面逻辑(对应你说的2:53场景)
        console.log("Displaying afternoon page");
    } else { 
        // 晚上或早7点前逻辑
        console.log("Displaying evening/pre-7AM page");
    } 
} else {
    // 非当日逻辑
    console.log("Not today");
}

额外说明

  1. 关于控制台无输出:既然你怀疑是Wikitude的限制,临时用alert(hour)替代console.log可以帮你确认当前小时是否被正确获取,方便调试。
  2. 小优化:只创建一次new Date()实例,既减少不必要的性能开销,也让代码更整洁。
  3. 严谨性优化:用严格相等运算符===替代==做日期比较,避免隐式类型转换带来的潜在问题。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.28 06:08:18