AppsDev AppsDev - 1 year ago 105
iOS Question

NSDate from string is always nil

I receive dates as

like this one:


I want to get its corresponding
object, and I'm trying this way:

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYY-MM-DDThh:mm:ss.s"
let date = dateFormatter.dateFromString(dateStr)

is like the example I wrote first. I took the
string from this page, but I get a
date, what is wrong there?

Thanks in advance

Answer Source

You have a few problems with your date format. First Y is for weekOfYear, D is for day of year. hh is used for 12 hours format, decimal second you should use capital S and you need to escape the 'T'

You should do as follow:

let dateString = "2016-05-20T12:25:00.0"

let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.S"
if let date = dateFormatter.dateFromString(dateString) {
    print(dateFormatter.stringFromDate(date) )  // "2016-05-20T12:25:00.0\n"