问题
How to use ISO8601DateFormatter to convert a String to Date?
let iSO8601DateFormatter = ISO8601DateFormatter()
let string = iSO8601DateFormatter.string(from: Date()) //2019-12-04T08:23:27Z
let date = iSO8601DateFormatter.date(from: string) //nil ?
The code above run in iPhone8 simulator with Xcode 11.2.1, I get nil.
But it works in the Playground of same Xcode.
Can any one help me to point what's wrong about my doing?
回答1:
It seems a bug in Xcode11 and swift 5. The date actually is not nil, but in debug, it is showed as nil.
let date = Date()
let formatter = ISO8601DateFormatter()
formatter.formatOptions = [.withInternetDateTime]
let dateString = formatter.string(from: date)
if let myDate = formatter.date(from: dateString){
print(myDate) //2019-12-08 02:22:26 +0000
}
You can see more about the bug at this SO post
回答2:
You can specify iSO8601 date formate to the NSDateFormatter to get Date:
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyyMMdd'T'HHmmssZ"
let date = dateFormatter.date(from: dateString)
print(date) //2019-12-04 12:46:00 +0000
You can check types of date formats at here.
I hope this may be helpful to you.
来源:https://stackoverflow.com/questions/59171939/dateformatter-iso8601dateformatter-can-not-get-date-from-string