Convert date string to NSDate

早过忘川 提交于 2019-12-12 03:46:27

问题


I've this string: "2016-10-08 00:20:00.000000". And I need it as an NSDate (Date for swift 3) object.

I've tried with the following:

let formatterJsonDate = DateFormatter()
formatterJsonDate.dateFormat = "yyy-MM-dd hh:mm:ss"

print(formatterJsonDate.date(from: "2016-10-08 00:20:00.000000"))

I always return nil value. What's wrong? I guess it's something about the date format.


回答1:


Your date format and your time string should be same. In your case it should be like,

 let formatterJsonDate = DateFormatter()
 formatterJsonDate.dateFormat = "yyy-MM-dd HH:mm:ss"

 print(formatterJsonDate.date(from: "2016-10-08 00:20:00"))

Or change dateformatter like,

  "yyyy-MM-dd HH:mm:ss.SSSSSS"

And hh should be capital for 24 - hour format!!!! like HH!




回答2:


If you want use nano seconds your code must be :

let formatterJsonDate = DateFormatter()
formatterJsonDate.dateFormat = "yyy-MM-dd hh:mm:ss.SSSS"
if let myDate = formatterJsonDate.date(from: "2016-10-08 00:20:00.000000")  {
    print(myDate)
} else {
    print ("Invalid Date")
}


来源:https://stackoverflow.com/questions/39912907/convert-date-string-to-nsdate

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