nil on conversion string to date [duplicate]

2019-09-26 03:59发布

This question already has an answer here:

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 :

enter image description here

what am I doing wrong ?

2条回答
再贱就再见
2楼-- · 2019-09-26 04:31

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

查看更多
Melony?
3楼-- · 2019-09-26 04:32

Try with

dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"//this your string date format
查看更多
登录 后发表回答