Date Format in Swift for Round-trip date/time pattern

511 views Asked by At

I am working on an iOS project with swift5 and encountered date format error as below.

"Date string does not match format expected by formatter."

I am using openapi-generator for swift5(https://github.com/OpenAPITools/openapi-generator/tree/master/samples/client/petstore/swift5/default) and it generated following formatter.

static let withoutSeconds: 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:ssZZZZZ"
    return formatter
}()

private func setup() {
    calendar = Calendar(identifier: .iso8601)
    locale = Locale(identifier: "en_US_POSIX")
    timeZone = TimeZone(secondsFromGMT: 0)
    dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZZZZZ"
}

override init() {
    super.init()
    setup()
}

required init?(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
    setup()
}

override public func date(from string: String) -> Date? {
    if let result = super.date(from: string) {
        return result
    }
    return OpenISO8601DateFormatter.withoutSeconds.date(from: string)
}

It works well but has above issue with datetime format

our api returns following json string as a datetime and I can't make it parse this string in above code.

"createdDate": "2020-03-01T05:42:15.0503394",
"updatedDate": "2020-09-02T07:06:56.6389018",

The datetime string that returned from our api seems has Roundtrip fromat specifier according to this document(https://learn.microsoft.com/en-us/dotnet/standard/base-types/standard-date-and-time-format-strings#Roundtrip)

Tried so many things but had no luck so far.

Thanks for your help in advance.

1

There are 1 answers

2
vadian On

Please have a closer look at the date string. There is no time zone (representing the Z specifier)?

This date format is supposed to work

yyyy-MM-dd'T'HH:mm:ss.S