nil on conversion string to date [duplicate]

2019-09-26 04:23发布

问题:

This question already has an answer here:

  • Converting NSString to NSDate (and back again) 17 answers

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