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

Swift 5 对比日期判断昼夜功能的条件逻辑错误排查修复

问题描述

实现了用于判断当前时间属于白天/夜晚的功能函数,逻辑为读取用户所处位置的精确日出、日落时间,与当前系统时间对比完成时段判定,目前运行存在异常:即使时间已过日落时刻,应用仍判定当前为白天,初步判断为if条件判断逻辑存在错误。
原有错误实现代码如下:

func actualTime(sunrise: Date, sunset: Date) {
    let date = Date()
    if (date < sunrise && date > sunset) {
        let nightTime = GrowingNotificationBanner(
            title: "Fuel Reserve AI: NIGHT-TIME".localised(),
            subtitle: "PlaneCalc applies nighttime fuel regulations".localised(),
            style: .warning
            
        )
        hapticWarning()
        nightTime.show()
    }
    else {
        let dayTime = GrowingNotificationBanner(
            title: "Fuel Reserve AI: DAY-TIME".localised(),
            subtitle: "PlaneCalc applies daytime fuel regulations".localised(),
            style: .success
        )
        dayTime.show()
    }
}
问题根因

核心错误为条件判断的逻辑运算符使用错误:

  • 正常时间流转下,同一天的日出时间永远早于日落时间,不存在任何一个时间点能同时满足「早于日出」且「晚于日落」,原代码使用&&(逻辑与)拼接两个互斥的判断条件,导致夜晚分支永远不会被触发,所有场景都会走到else分支判定为白天。
  • 夜晚的合法时间区间实际为两段:当日日出之前、当日日落之后,两个区间满足任意一个即属于夜晚。
修复方案
  • 将原条件中错误的&&(逻辑与)替换为||(逻辑或),正确覆盖夜晚的两个时间区间
  • 增加入参合法性校验,避免上游传入的日出、日落时间顺序颠倒导致判定失效
  • 需额外确认传入的日出、日落时间与系统当前时间时区一致,避免时区偏移带来的判定误差
修正后代码
func actualTime(sunrise: Date, sunset: Date) {
    // 入参合法性校验:保证日出时间早于日落时间
    guard sunrise < sunset else {
        print("日出/日落时间参数异常,无法完成时段判定")
        return
    }
    
    let currentDate = Date()
    // 满足「早于日出」或「晚于日落」任意条件即为夜晚
    if currentDate < sunrise || currentDate > sunset {
        let nightTime = GrowingNotificationBanner(
            title: "Fuel Reserve AI: NIGHT-TIME".localised(),
            subtitle: "PlaneCalc applies nighttime fuel regulations".localised(),
            style: .warning
        )
        hapticWarning()
        nightTime.show()
    } else {
        let dayTime = GrowingNotificationBanner(
            title: "Fuel Reserve AI: DAY-TIME".localised(),
            subtitle: "PlaneCalc applies daytime fuel regulations".localised(),
            style: .success
        )
        dayTime.show()
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.29 03:09:39