如何使用Swift4中的Codable转换带有可选小数秒的日期字符串

时间:2017-09-27 23:02:58

标签: swift swift4 nsdateformatter codable dateformatter

我正在使用Swift的Codable替换旧的JSON解析代码,并且遇到了一些麻烦。我想这不是一个Codable问题,因为它是一个DateFormatter问题。

以结构

开头
 struct JustADate: Codable {
    var date: Date
 }

和json字符串

let json = """
  { "date": "2017-06-19T18:43:19Z" }
"""

现在允许解码

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601

let data = json.data(using: .utf8)!
let justADate = try! decoder.decode(JustADate.self, from: data) //all good

但是如果我们更改日期以使其具有小数秒,例如:

let json = """
  { "date": "2017-06-19T18:43:19.532Z" }
"""

现在它破了。日期有时会以小秒数回归,有时则不会。我以前解决它的方式是在我的映射代码中我有一个转换函数,它尝试使用和不使用小数秒的dateFormats。我不太确定如何使用Codable来处理它。有什么建议吗?

4 个答案:

答案 0 :(得分:31)

您可以使用两种不同的日期格式化程序(有和没有分数秒)并创建自定义DateDecodingStrategy。如果在解析API返回的日期时出现故障,您可以按照@PauloMattos在评论中的建议抛出DecodingError:

iOS 9,macOS 10.9,tvOS 9,watchOS 2,Xcode 9或更高版本

自定义ISO8601 DateFormatter:

extension Formatter {
    static let iso8601: DateFormatter = {
        let formatter = DateFormatter()
        formatter.calendar = Calendar(identifier: .iso8601)
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.timeZone = TimeZone(secondsFromGMT: 0)
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX"
        return formatter
    }()
    static let iso8601noFS: DateFormatter = {
        let formatter = DateFormatter()
        formatter.calendar = Calendar(identifier: .iso8601)
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.timeZone = TimeZone(secondsFromGMT: 0)
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssXXXXX"
        return formatter
    }()
}

自定义DateDecodingStrategyError

extension JSONDecoder.DateDecodingStrategy {
    static let customISO8601 = custom {
        let container = try $0.singleValueContainer()
        let string = try container.decode(String.self)
        if let date = Formatter.iso8601.date(from: string) ?? Formatter.iso8601noFS.date(from: string) {
            return date
        }
        throw DecodingError.dataCorruptedError(in: container, debugDescription: "Invalid date: \(string)")
    }
}

自定义DateEncodingStrategy

extension JSONEncoder.DateEncodingStrategy {
    static let customISO8601 = custom {
        var container = $1.singleValueContainer()
        try container.encode(Formatter.iso8601.string(from: $0))
    }
}

修改/更新

Xcode 9•Swift 4•iOS 11或更高版本

ISO8601DateFormatter现在支持iOS11或更高版本中的formatOptions .withFractionalSeconds

extension Formatter {
    static let iso8601: ISO8601DateFormatter = {
        let formatter = ISO8601DateFormatter()
        formatter.formatOptions = [.withInternetDateTime, .withFractionalSeconds]
        return formatter
    }()
    static let iso8601noFS = ISO8601DateFormatter()
}

海关DateDecodingStrategyDateEncodingStrategy与上面显示的相同。

// Playground testing
struct ISODates: Codable {
    let dateWith9FS: Date
    let dateWith3FS: Date
    let dateWith2FS: Date
    let dateWithoutFS: Date
}
let isoDatesJSON = """
{
"dateWith9FS": "2017-06-19T18:43:19.532123456Z",
"dateWith3FS": "2017-06-19T18:43:19.532Z",
"dateWith2FS": "2017-06-19T18:43:19.53Z",
"dateWithoutFS": "2017-06-19T18:43:19Z",
}
"""
let isoDatesData = Data(isoDatesJSON.utf8)

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .customISO8601

do {
    let isoDates = try decoder.decode(ISODates.self, from: isoDatesData)
    print(Formatter.iso8601.string(from: isoDates.dateWith9FS))   // 2017-06-19T18:43:19.532Z
    print(Formatter.iso8601.string(from: isoDates.dateWith3FS))   // 2017-06-19T18:43:19.532Z
    print(Formatter.iso8601.string(from: isoDates.dateWith2FS))   // 2017-06-19T18:43:19.530Z
    print(Formatter.iso8601.string(from: isoDates.dateWithoutFS)) // 2017-06-19T18:43:19.000Z
} catch {
    print(error)
}

答案 1 :(得分:2)

雨燕5

要将日期解析为ISO8601字符串,必须使用DateFormatter。在更新的系统(例如iOS11 +)中,您可以使用ISO8601DateFormatter。

只要您不知道日期是否包含毫秒,就应该为每种情况创建2个格式化程序。然后,在将String解析为Date的过程中,请同时使用两者。

适用于旧系统的DateFormatter

/// Formatter for ISO8601 with milliseconds
lazy var iso8601FormatterWithMilliseconds: DateFormatter = {
    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

    return dateFormatter
}()

/// Formatter for ISO8601 without milliseconds
lazy var iso8601Formatter: DateFormatter = {
    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US_POSIX")
    dateFormatter.timeZone = TimeZone(abbreviation: "GMT")
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZZZZZ"

    return dateFormatter
}()

用于较新系统的ISO8601DateFormatter(例如iOS 11 +)

lazy var iso8601FormatterWithMilliseconds: ISO8601DateFormatter = {
    let formatter = ISO8601DateFormatter()

    // GMT or UTC -> UTC is standard, GMT is TimeZone
    formatter.timeZone = TimeZone(abbreviation: "GMT")
    formatter.formatOptions = [.withInternetDateTime,
                               .withDashSeparatorInDate,
                               .withColonSeparatorInTime,
                               .withTimeZone,
                               .withFractionalSeconds]

    return formatter
}()

/// Formatter for ISO8601 without milliseconds
lazy var iso8601Formatter: ISO8601DateFormatter = {
    let formatter = ISO8601DateFormatter()

    // GMT or UTC -> UTC is standard, GMT is TimeZone
    formatter.timeZone = TimeZone(abbreviation: "GMT")
    formatter.formatOptions = [.withInternetDateTime,
                               .withDashSeparatorInDate,
                               .withColonSeparatorInTime,
                               .withTimeZone]

    return formatter
}()

摘要

您会注意到有2个格式化程序要创建。如果要支持较旧的系统,则可以使用4种格式化程序。为了使其更简单,请查看Tomorrow on GitHub,在这里您可以看到此问题的完整解决方案。

要将字符串转换为日期,请使用:

let date = Date.fromISO("2020-11-01T21:10:56.22+02:00")

答案 2 :(得分:1)

一个新选项(从Swift 5.1开始)是Property Wrapper。 CodableWrappers库提供了一种解决此问题的简便方法。

对于默认的ISO8601

@ISO8601DateCoding 
struct JustADate: Codable {
    var date: Date
 }

如果要自定义版本:

// Custom coder
@available(macOS 10.12, iOS 10.0, watchOS 3.0, tvOS 10.0, *)
public struct FractionalSecondsISO8601DateStaticCoder: StaticCoder {

    private static let iso8601Formatter: ISO8601DateFormatter = {
        let formatter = ISO8601DateFormatter()
        formatter.formatOptions = .withFractionalSeconds
        return formatter
    }()

    public static func decode(from decoder: Decoder) throws -> Date {
        let stringValue = try String(from: decoder)
        guard let date = iso8601Formatter.date(from: stringValue) else {
            throw DecodingError.dataCorrupted(DecodingError.Context(codingPath: decoder.codingPath, debugDescription: "Expected date string to be ISO8601-formatted."))
        }
        return date
    }

    public static func encode(value: Date, to encoder: Encoder) throws {
        try iso8601Formatter.string(from: value).encode(to: encoder)
    }
}
// Property Wrapper alias
public typealias ISO8601FractionalDateCoding = CodingUses<FractionalSecondsISO8601DateStaticCoder>

// Usage
@ISO8601FractionalDateCoding
struct JustADate: Codable {
    var date: Date
 }

答案 3 :(得分:0)

除了@Leo的回答,如果您需要为旧操作系统提供支持(ISO8601DateFormatter仅适用于iOS 10,Mac OS 10.12),您可以编写自定义格式化程序,在解析字符串时使用两种格式:

class MyISO8601Formatter: DateFormatter {

    static let formatters: [DateFormatter] = [
        iso8601Formatter(withFractional: true),
        iso8601Formatter(withFractional: false)
        ]

    static func iso8601Formatter(withFractional fractional: Bool) -> DateFormatter {
        let formatter = DateFormatter()
        formatter.calendar = Calendar(identifier: .iso8601)
        formatter.locale = Locale(identifier: "en_US_POSIX")
        formatter.timeZone = TimeZone(secondsFromGMT: 0)
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss\(fractional ? ".SSS" : "")XXXXX"
        return formatter
    }

    override public func getObjectValue(_ obj: AutoreleasingUnsafeMutablePointer<AnyObject?>?,
                                 for string: String,
                                 errorDescription error: AutoreleasingUnsafeMutablePointer<NSString?>?) -> Bool {
        guard let date = (type(of: self).formatters.flatMap { $0.date(from: string) }).first else {
            error?.pointee = "Invalid ISO8601 date: \(string)" as NSString
            return false
        }
        obj?.pointee = date as NSDate
        return true
    }

    override public func string(for obj: Any?) -> String? {
        guard let date = obj as? Date else { return nil }
        return type(of: self).formatters.flatMap { $0.string(from: date) }.first
    }
}

,您可以将其用作日期解码策略:

let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(MyISO8601Formatter())

虽然实现起来有点迷人,但这样做的好处是可以与Swift在数据格式错误时抛出的解码错误保持一致,因为我们不会改变错误报告机制。

例如:

struct TestDate: Codable {
    let date: Date
}

// I don't advocate the forced unwrap, this is for demo purposes only
let jsonString = "{\"date\":\"2017-06-19T18:43:19Z\"}"
let jsonData = jsonString.data(using: .utf8)!
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .formatted(MyISO8601Formatter())
do {
    print(try decoder.decode(TestDate.self, from: jsonData))
} catch {
    print("Encountered error while decoding: \(error)")
}

将打印TestDate(date: 2017-06-19 18:43:19 +0000)

添加小数部分

let jsonString = "{\"date\":\"2017-06-19T18:43:19.123Z\"}"

将产生相同的输出:TestDate(date: 2017-06-19 18:43:19 +0000)

但是使用了错误的字符串:

let jsonString = "{\"date\":\"2017-06-19T18:43:19.123AAA\"}"
如果数据不正确,

将打印默认的Swift错误:

Encountered error while decoding: dataCorrupted(Swift.DecodingError.Context(codingPath: [__lldb_expr_84.TestDate.(CodingKeys in _B178608BE4B4E04ECDB8BE2F689B7F4C).date], debugDescription: "Date string does not match format expected by formatter.", underlyingError: nil))