How to handle multiple date formats?

|▌冷眼眸甩不掉的悲伤 提交于 2019-11-28 14:15:17

Check if the date string contains a slash and set the date format accordingly:

if mydate.contains("/") {
    df.dateFormat = "MM/dd/yyyy"
}  else {
    df.dateFormat = "yyyy-MM-dd HH:mm:ss Z"
}

You can try an approach that is very clean in your code. You can add this extension:

extension DateFormatter {

    func dateFromMultipleFormats(fromString dateString: String) -> Date? {
        var formats: [String] = [
        "yyyy-MM-dd hh:mm:ss.SSSSxx",
        "yyyy-MM-dd hh:mm:ss.SSSxxx",
        "yyyy-MM-dd hh:mm:ss.SSxxxx",
        "yyyy-MM-dd hh:mm:ss.Sxxxxx",
        "yyyy-MM-dd hh:mm:ss"
        ]
    for format in formats {
        self.dateFormat = format
        if let date = self.date(from: dateString) {
                return date
            }
        }
        return nil
    }
}

then just try changing the formats array in the function to whatever formats you may need. Now just use your formatter like this:

if let myDate = dateFormatter.dateFromMultipleFormats(fromString: mydate) {
    print("success!")
} else {
    print("add another format for \(mydate)")
}

I think the best way to do this is using two DateFormatters, one for iso8601 format and other for this short format.

(My code below uses an extension of DateFormatter, but you can use a method / helper / anything else with these two formatters).

Swift 3

extension DateFormatter {
    static let iso8601DateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.calendar = Calendar.current // Set the Calendar
        formatter.timeZone = TimeZone(secondsFromGMT: 0) // Set the timezone
        formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss'Z'"
        return formatter
    }()

    static let shortDateFormatter: DateFormatter = {
        let formatter = DateFormatter()
        formatter.calendar = Calendar.current // Set the Calendar
        formatter.timeZone = TimeZone(secondsFromGMT: 0) // Set the timezone
        formatter.dateFormat = "MM/dd/yyyy"
        return formatter
    }()

    static func date(string: String) -> Date? {
        if let iso8601Date = iso8601DateFormatter.date(from: string) {
            return iso8601Date
        } else if let shortDate = shortDateFormatter.date(from: string) {
            return shortDate
        } else {
            return nil
        }
    }
}
标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!