Swift iOS开发String转Date结果异常问题求助
问题根因
核心错误来自日期格式符的使用不当,共两处问题:
YYYY是ISO周年纪年格式符,对应周所属的年份,而非公历年,你需要替换为表示公历年的yyyy。这也是你转换2021年5月的日期,却得到2020年12月结果的直接原因。HH是24小时制的小时格式符,与你代码中搭配的上午/下午标识a冲突,需要替换为12小时制的小时格式符h。
你提到的目标格式
"May 5, 2020 9:20 5:39:15 PM"存在明显笔误,若实际格式为月 日, 年 时:分:秒 上午/下午,和你的测试用例"May 5, 2021 1:34:15 AM"一致,调整格式符后即可正常解析。
修复后的代码
extension String { func toDate(withFormat format: String = "MMM d, yyyy h:mm:ss a") -> Date { let dateFormatter = DateFormatter() dateFormatter.locale = Locale(identifier: "en_US") dateFormatter.calendar = Calendar(identifier: .iso8601) // 若需要固定为美国东海岸时区,可替换为 dateFormatter.timeZone = TimeZone(identifier: "America/New_York") dateFormatter.timeZone = .current dateFormatter.dateFormat = format guard let date = dateFormatter.date(from: self) else { preconditionFailure("Check the format!!!") } return date } }
补充说明
直接打印Date类型默认输出UTC时区的时间,你看到的和东海岸时区有差异属于正常现象,如果需要展示东海岸时区的时间字符串,使用对应时区的DateFormatter格式化输出即可。
内容的提问来源于stack exchange,提问作者Cam
相关产品推荐
相关产品推荐

