Search code examples
swiftxcodedatetimensdateformatterbeta

Is ISO8601DateFormatter broken in iOS14 and MacOS 11?


I'm experimenting with the latest beta after WWDC.

ISO8601DateFormatter().date(from:"2017-12-18T11:30:26.000Z") should return a date. Instead it is returning nil. This worked in iOS 13.

I broke it down and tested it in Swift Playground. I'm working with Xcode Version 12.0 beta (12A6159)

let testString = "2017-12-18T11:30:26.000Z"
let testString2 = "2017-12-18"
let testFormatter = ISO8601DateFormatter()
let testDate1 = testFormatter.date(from: testString)
let testDate2 = testFormatter.date(from: testString2)

testDate1 and testDate2 should be dates, they are nils.

testFormatter is partly functional. The line below returns the current date as a string as expected; "2020-06-27T18:53:39Z".

let testDate3 = testFormatter.string(from: Date())

Am I missing something here, or is this just an early beta bug? I have filed a Feedback with Apple, but I'm hoping someone here has an answer.


Solution

  • The code you posted doesn't work in iOS 13 as well.

    Try the following:

    let testString = "2017-12-18T11:30:26.000Z"
    let testString2 = "2017-12-18"
    let testFormatter = ISO8601DateFormatter()
    
    testFormatter.formatOptions = [
        .withFullDate,
        .withFullTime,
        .withFractionalSeconds,
    ]
    let testDate1 = testFormatter.date(from: testString)
    
    testFormatter.formatOptions = [.withFullDate]
    let testDate2 = testFormatter.date(from: testString2)