如何处理多种日期格式?

4th*_*ace 4 date swift swift3

2016-12-27 14:40:46 +0000当我到达下面的 df.date() 行时,使用此格式的日期时应用程序崩溃:

致命错误:在解包可选值时意外发现 nil

我也看到了这一点:

错误:执行被中断,原因:EXC_BAD_INSTRUCTION(代码=EXC_I386_INVOP,子代码=0x0)

我有可以采用这种格式的字符串

12/27/2016
Run Code Online (Sandbox Code Playgroud)

但有时以这种格式

2016-12-27 14:40:46 +0000      
Run Code Online (Sandbox Code Playgroud)

以下是在上述格式上崩溃的代码片段:

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)
Run Code Online (Sandbox Code Playgroud)

如何使用基本上一个函数来处理这两种格式?

vad*_*ian 5

检查日期字符串是否包含斜杠并相应地设置日期格式:

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