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

Swift中符合dd/MM/yyyy格式的合法日期用DateFormatter转换返回nil

问题原因

该问题由巴西夏令时切换导致:1986、1987年巴西夏令时生效时间为10月25日0点,当日00:00:00会直接跳转为01:00:00,你指定的BRT时区下,25/10/1986默认对应的0点时间不存在,因此DateFormatter返回nil。

解决方案

可任选以下方案修复:

  • 开启DateFormatter宽松解析,自动将不存在的时间顺延到合法时间点:
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "pt_BR")
formatter.timeZone = TimeZone(abbreviation: "BRT")
formatter.dateFormat = "dd/MM/yyyy"
formatter.isLenient = true

print(formatter.date(from: "25/10/1986"))
  • 给日期补充非跳转时段的时间信息,避免匹配到不存在的0点:
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "pt_BR")
formatter.timeZone = TimeZone(abbreviation: "BRT")
formatter.dateFormat = "dd/MM/yyyy HH:mm"

print(formatter.date(from: "25/10/1986 12:00"))
  • 若不需要严格对应巴西本地时区时间,直接使用GMT时区转换:
let formatter = DateFormatter()
formatter.locale = Locale(identifier: "pt_BR")
formatter.timeZone = TimeZone(secondsFromGMT: 0)
formatter.dateFormat = "dd/MM/yyyy"

print(formatter.date(from: "25/10/1986"))

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 15:27:03