DateFormatter/ISO8601DateFormatter can not get date from string [duplicate]

非 Y 不嫁゛ 提交于 2020-12-13 04:51:30

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!