2017-03-06 101 views
-1

我正在使用錯誤的文檔構造dateFormat來分析預定義格式的時間。 maddy(下)提供了正確文檔的鏈接。正確構建dateFormat在Swift 3.1中使用DateFormatter解析時間

這裏的時候我使用了錯誤的格式發生了什麼:

var idf = DateFormatter() 
idf.locale = Locale(identifier: "en_US") 
idf.dateStyle = .none 
idf.dateFormat = "hh:MM:SSa" 

// Of the variables defined here, the only one that doesn't cause an error 
// is the last one: 
var sMidnight: String = "12:00:00AM" 
var sEarly: String = "12:40:22AM" 
var sMorning: String = "6:00:00AM" 
var sNoon: String = "12:00:00PM" 
var sAfternoon: String = "12:30:22PM" 
var sEvening: String = "7:05:45PM" 

// Put any of the variables besides sEvening here and you get a crash. 
// "fatal error: unexpectedly found nil while unwrapping an Optional value" 
var date: Date = idf.date(from: sEvening)! 

print(idf.string(from: date)) // prints 07:05:45 PM 
+2

請參閱關於格式說明符的文檔。你正在使用錯誤的。 – rmaddy

回答

3

MM是2位數的月份數。 SS是用於小數秒。請查看與格式說明符相關的the documentation

你想:

"h:mm:ssa" 

您的格式。

+0

謝謝。我無法找到正確的文檔。這解決了這個問題。 –

+0

很高興幫助。請不要忘記接受解決您問題的答案。看來你還沒有關閉你的任何問題。 – rmaddy