How to handle two possible date formats?

2019-03-01 11:36发布

问题:

My app calls a web api that sometimes returns json dates in this format:

"2017-01-18T10:49:00Z"

and sometimes in this format:

"2017-02-14T19:53:38.1173228Z"

I can use the following dateformat to convert the 2nd one to a Date object:

formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

But of course it doesn't work for the 1st one.

I've tried utilities like https://github.com/melvitax/DateHelper to see if it will work, but I haven't found a way to convert a json date (in any format) into a Date object.

Any recommendations?

回答1:

Try both formats:

let parser1 = DateFormatter()
parser1.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"

let parser2 = DateFormatter()
parser2.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

func parse(_ dateString: String) -> Date? {
    let parsers = [parser1, parser2]

    for parser in parsers {
        if let result = parser.date(from: dateString) {
            return result
        }
    }

    return nil
}

print(parse("2017-01-18T10:49:00Z"))
print(parse("2017-02-14T19:53:38.1173228Z"))

Also note that the Z in the format is not a literal value.