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

Swift解码JSON时如何去除epoch时间戳末尾多余的000

问题原因

你遇到的解析错误是因为单位不匹配:JSON返回的birthdate字段是毫秒级Unix时间戳(即从1970年1月1日0点至今的毫秒数),而你给JSONDecoder设置的解析策略是.secondsSince1970(秒级时间戳),二者相差1000倍,所以最终解析出来的日期会错误显示为五万多年后。

解决方案

方案1:使用毫秒级内置解析策略

如果你的接口所有时间戳都是毫秒级,直接修改解码策略即可:

class Person : Codable {
    var birthdate: Date = Date()
}

var json: String = """
{
    "birthdate": 1627516800000
}
"""

let decoder = JSONDecoder()
// 替换为毫秒级时间戳解析策略
decoder.dateDecodingStrategy = .millisecondsSince1970

let people = try! decoder.decode(Person.self, from: json.data(using: .utf8)!)
print(people.birthdate) // 输出 2021-07-29 00:00:00 +0000,结果正确

方案2:自定义兼容双单位的解析策略

如果接口返回的时间戳存在秒级、毫秒级混合的情况,可以写自定义解析逻辑自动适配:

decoder.dateDecodingStrategy = .custom({ decoder in
    let container = try decoder.singleValueContainer()
    let timeStamp = try container.decode(Double.self)
    // 数值大于1e12判定为毫秒级,除以1000后再转Date
    return timeStamp > 1000000000000 ? Date(timeIntervalSince1970: timeStamp / 1000) : Date(timeIntervalSince1970: timeStamp)
})

注意:你提供的JSON示例中"birthdate": 1627516800000,末尾多余的逗号不符合标准JSON语法,实际使用时需要删除,避免触发解析错误。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 19:15:03