iOS 15下Swift比较服务器日期异常:全部判定为过去
问题分析与解决思路
首先,你的代码里用Date.compare判断“今日”完全不可行——Date是精确到毫秒的时间戳,只有当服务器返回的日期和Date.now毫秒级完全一致时才会返回"today",这种情况几乎不可能发生,这是核心问题之一。
其次,所有日期被判定为“past”,大概率是时区或日期精度问题:
- 服务器返回的ISO8601字符串可能只有日期部分(比如
2024-05-20),没有时分秒和时区信息。iOS的ISO8601DateDecoder默认会把这种无时区的字符串解析成UTC时区的当天0点。假设你在东八区,当前本地时间是2024-05-20 14:00,对应的UTC时间是2024-05-20 06:00,那解析后的gameDate是UTC 0点,时间戳比当前UTC时间早6小时,自然会被判定为orderedAscending(过去)。 - 就算服务器返回了带时分秒的日期,但如果时区是UTC,直接用
Date.compare对比本地时间的“今日”也会出现偏差。
修正方案
把判断逻辑改成用Calendar处理日期的“天”维度对比,而非直接比较时间戳:
func getDetails(for game: Game) -> String { let now = Date.now let gameDate = game.gameDate let calendar = Calendar.current // 判断是否为今日 if calendar.isDate(gameDate, inSameDayAs: now) { print("today") return "today" } // 判断过去/未来 if gameDate < now { print("past") return "past" } else { print("future") return "future" } }
额外排查步骤
打印日期的本地时区详细信息,确认解析是否正确:
print("Game Date: \(gameDate.description(with: .current))") print("Now: \(Date.now.description(with: .current))")直观查看两个日期在本地时区的具体时间,判断解析结果是否符合预期。
若服务器返回的无时区日期实际代表本地时区的当天,调整解码器策略:
let decoder = JSONDecoder() let formatter = ISO8601DateFormatter() formatter.formatOptions = [.withFullDate, .withDashSeparatorInDate] formatter.timeZone = TimeZone.current // 设置为本地时区 decoder.dateDecodingStrategy = .formatted(formatter)
内容的提问来源于stack exchange,提问作者dreadbot
相关产品推荐
相关产品推荐

