2016-12-27 52 views
1

當我到下面的df.date()線,當這種格式2016-12-27 14:40:46 +0000日期使用應用程序崩潰:如何處理多種日期格式?

fatal error: unexpectedly found nil while unwrapping an Optional value

而且我也看到了這一點:

error: Execution was interrupted, reason: EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)

我有字符串可以在這個格式

12/27/2016 

,但有時這種格式

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

以下是代碼片段,上述格式崩潰:

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) 

如何處理基本上使用一種功能兩種格式?

+1

'數據(來自:)'返回一個可選的,你可以嘗試* *使用第一格式從字符串得到'Date',如果返回零,嘗試其他格式化程序。最後一行不能編譯,我懷疑它會崩潰,沒有力量解開 – luk2302

+1

使用兩個格式化器,嘗試一個,然後另一個。 – Sulthan

+0

相關http://stackoverflow.com/questions/14877489/how-to-parse-iso-8601-using-nsdateformatter-with-optional-milliseconds-part – Sulthan

回答

3

檢查日期字符串包含一個斜槓,並相應設置日期格式:

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

我認爲要做到這一點的最好辦法是使用2 DateFormatters,一個用於ISO8601格式和其他這麼短的格式。

(我的代碼使用DateFormatter的擴展名,但您可以使用這兩個格式化程序的方法/輔助程序/其他任何東西)

斯威夫特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 
     } 
    } 
} 
2

您可以嘗試的方法是在你的代碼非常乾淨。您可以添加此擴展名:

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 
    } 
} 

那麼就嘗試改變格式數組中的功能,你可能需要的任何格式。 現在只需使用您的格式是這樣的:

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