nil on conversion string to date [duplicate]

半世苍凉 提交于 2019-12-13 09:55:15

问题


I try to convert string to date

my method looks like this

func createDateFromString(string: String) -> NSDate {

    let dateFormatter = NSDateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"//this your string date format
    let date = dateFormatter.dateFromString(string)

    return date!
}

But I have a runtime a error.

fatal error: unexpectedly found nil while unwrapping an Optional value

String is not empty :

what am I doing wrong ?


回答1:


You should just remove .SSS from dateFormat and implicit unwrapping to avoid fatal error (function should return optional value).




回答2:


Try with

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"//this your string date format


来源:https://stackoverflow.com/questions/37986288/nil-on-conversion-string-to-date

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