使用nextDate反向查找日期异常跳至1995年,是否为Bug?
问题分析与解决
这不是Bug,是你对nextDate(after:matching:matchingPolicy:direction:)方法的参数逻辑理解有疏漏。
问题原因
你使用的matchingPolicy: .previousTimePreservingSmallerComponents策略,会要求匹配的日期不仅满足day:23的条件,还要尽可能保留原日期的时间部分(比如你原日期对应斯德哥尔摩时区的02:00)。当系统在2022年9月23日寻找该时间点时,因组件约束不足,策略的回溯逻辑出现偏差,最终返回了更早年份的结果。
更关键的是:如果你只是想获取指定日期的上月23日,nextDate并非最优选择——这种场景下直接构造日期组件计算更可靠。
解决方法
方法一:直接构造日期组件(推荐)
通过提取原日期的年月信息,直接生成上月23日的日期:
var calendar: Calendar = .autoupdatingCurrent calendar.timeZone = TimeZone(identifier: "Europe/Stockholm")! let date = Date(timeIntervalSince1970: 1666310400.0) // "Oct 21, 2022 at 2:00 AM"(斯德哥尔摩时间) // 提取原日期的年、月组件 var targetComponents = calendar.dateComponents([.year, .month], from: date) // 月份减1,设置日期为23日 targetComponents.month! -= 1 targetComponents.day = 23 // 生成目标日期 let targetDate = calendar.date(from: targetComponents) print(targetDate!) // 输出:2022-09-23 00:00:00 +0000(对应斯德哥尔摩时间02:00)
方法二:调整nextDate的匹配策略
如果一定要用nextDate,将匹配策略改为.strict,系统会直接查找最近的符合day:23的日期,不会触发不必要的回溯逻辑:
var calendar: Calendar = .autoupdatingCurrent calendar.timeZone = TimeZone(identifier: "Europe/Stockholm")! let date = Date(timeIntervalSince1970: 1666310400.0) let targetDate = calendar.nextDate(after: date, matching: DateComponents(day: 23), matchingPolicy: .strict, direction: .backward) print(targetDate!) // 输出:2022-09-23 00:00:00 +0000(对应斯德哥尔摩时间02:00)
内容的提问来源于stack exchange,提问作者netdigger
相关产品推荐
相关产品推荐

