2015-12-22 62 views
0

對於某些值,我得到nil,而在swift中使用dateFromString。我搜查了很多,但徒勞無功。dateFromString對於某些值返回nil

以下是我的代碼:

let strDate = self.sortedDict.valueForKey("TIME").objectAtIndex(indexPath.row).objectAtIndex(0) as? String 
     print(strDate); 

     let st_date = frmt.dateFromString(strDate!) 

     let frmt1:NSDateFormatter = NSDateFormatter() 
     frmt1.locale = NSLocale(localeIdentifier: localeStr) 
     frmt1.dateFormat = "MMM, dd yyyy hh:mm a" 
     if st_date != nil { 
      print(st_date) 
} 

輸出控制檯:

Optional("September, 20 2015 10:00:00") 
Optional(2015-09-20 10:00:00 +0000) 

Optional("October, 04 2015 10:00:00") 
Optional(2015-10-04 10:00:00 +0000) 

Optional("October, 04 2015 14:00:00") // nil 
Optional("October, 18 2015 15:00:00") // nil 
Optional("September, 20 2015 14:00:00") // nil 

Optional("September, 27 2015 10:00:00") 
Optional(2015-09-27 10:00:00 +0000) 
Optional("September, 27 2015 12:00:00") 
Optional(2015-09-27 00:00:00 +0000) 
Optional("September, 27 2015 14:00:00") 

Optional("October, 03 2015 14:00:00") //nil 
Optional("October, 03 2015 16:00:00") //nil 

的格式與所有日期字符串我仍然得到零的幾個值。爲什麼這樣?請幫忙。我哪裏錯了?

+0

可選(「2015年9月27日14:00:00」) - 那個不返回零?你確定? – gnasher729

+0

這不是你的實際代碼,對吧? – gnasher729

+0

是的,這是我的實際代碼,它適用於可選(「2015年9月27日14:00:00」) – z22

回答

4

格式應該是HH 24小時,即使你只得到12小時的值。

frmt1.dateFormat = "MMM, dd yyyy HH:mm a" 
+0

感謝隊友,它工作 – z22

+0

那麼爲什麼可選(「9月27日2015年14:00:00」)工作? – gnasher729

+0

@ gnasher729這可能會寫成問題。它不應該適用於12小時格式。 –

相關問題