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

Swift中如何将服务端返回的日期字符串转换为正确的Date类型?

问题原因

  • 日期格式字符串匹配错误:服务端返回的日期末尾带Z标识,代表UTC时区,你的格式串未包含该匹配项,同时你写的SSSS代表4位毫秒,但示例中的毫秒只有3位,格式不匹配直接导致解析结果为nil。
  • 时区配置错误:你将formatter的时区设为.current(本地时区),但服务端返回的是UTC标准时间,解析时时区不匹配会导致转换后的时间出现偏差。
  • 缺少固定区域配置:如果用户设备设置为12小时制等非标准区域格式,即使格式串正确也可能出现解析失败,需要强制指定locale避免系统设置影响解析结果。

修复后的代码

import Foundation
struct TimeManager{
    static func editTime(withTime time:String) {
        let serverDateFormatter:DateFormatter = {
            let result = DateFormatter()
            // 固定locale避免系统区域设置影响解析
            result.locale = Locale(identifier: "en_US_POSIX")
            // 补充Z匹配UTC标识,3位毫秒用SSS
            result.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
            // 服务端返回的是UTC时间,解析时必须用UTC时区
            result.timeZone = TimeZone(secondsFromGMT: 0)
            return result
        }()
        let date = "2021-09-08T20:52:47.001Z"
        let dateformat = serverDateFormatter.date(from: date)
        print(dateformat)
    }
}

后续时间展示注意事项

解析得到的Date类型本身是不带时区的,如果你需要展示给用户看,再单独创建一个用于展示的DateFormatter,将时区设为.current配置你需要的展示格式即可,不要将解析用的formatter和展示用的formatter混用,避免出现时区偏差。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.01 21:06:03