我想字符串轉換成NSDate的與此代碼零的NSDate從DateFormatter
let dateString = data as! String
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = formatter.date(from: dateString)
let Calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
let unitFlags: NSCalendar.Unit = [.hour, .day, .month, .year]
let components = Calendar?.components(unitFlags, from: date!)
和dateString
是"2017-04-03T18:50:34.3042751+04:30"
,但我發現fatal error: unexpectedly found nil while unwrapping an Optional value
最後一行。我究竟做錯了什麼?
您的日期格式與您的日期格式不匹配 –
「」2017-04-03T18:50:34.3042751 + 04:30「'應該是'「yyyy-MM-dd'T'HH:mm:ss.SSSSSSSXXXXX」' –
'「yyyy-MM-dd'T'HH:mm:ss.SSSXXXXX」'也應該可以工作 –