简体   繁体   English

如何处理多种日期格式?

[英]How to handle multiple date formats?

When I get to the df.date() line below, the app crashes when a date with this format 2016-12-27 14:40:46 +0000 is used: 当我到达下面的df.date()行时,当使用具有以下格式的日期2016-12-27 14:40:46 +0000时,应用程序崩溃:

fatal error: unexpectedly found nil while unwrapping an Optional value 致命错误:解开Optional值时意外发现nil

And I also see this: 我也看到了这一点:

error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0) 错误:执行被中断,原因:EXC_BAD_INSTRUCTION(代码= EXC_I386_INVOP,子代码= 0x0)

I have strings that can be in this format 我有可以采用这种格式的字符串

12/27/2016

but sometimes in this format 但有时采用这种格式

2016-12-27 14:40:46 +0000      

Here is the code snippet that crashes on the above format: 这是在上述格式下崩溃的代码段:

let mydate = "12/27/2016" //this works but not the longer format
let df = DateFormatter()
df.dateFormat = "MM/dd/yyyy" //this is the format I want both dates to be in
newDate:Date = df.date(from: mydate)

How do I handle both formats using basically one function? 我如何使用一个功能处理两种格式?

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. 然后只需尝试将函数中的formats数组更改为您可能需要的任何格式。 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. 我认为最好的方法是使用两个DateFormatters ,一个用于iso8601格式,另一个用于这种短格式。

(My code below uses an extension of DateFormatter, but you can use a method / helper / anything else with these two formatters) . (下面的代码使用DateFormatter的扩展名,但是这两个格式化程序可以使用method / helper /其他任何方法)

Swift 3 迅捷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
        }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM