Reputation: 12499
I receive dates as String
like this one:
"2016-05-20T12:25:00.0"
I want to get its corresponding NSDate
object, and I'm trying this way:
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "YYYY-MM-DDThh:mm:ss.s"
let date = dateFormatter.dateFromString(dateStr)
where dateStr
is like the example I wrote first. I took the dateFormat
string from this page, but I get a nil
date, what is wrong there?
Thanks in advance
Upvotes: 0
Views: 142
Reputation: 189
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.S"
if let date = dateFormatter.stringFromDate(NSDate()) {
print(dateFormatter.stringFromDate(date) )
}
Upvotes: 0
Reputation: 236295
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"
}
Upvotes: 4