0

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

AppsDev
  • 12,319
  • 23
  • 93
  • 186
  • confirm that your dateStr format and your setter format is right or not – Nitin Gohel May 26 '16 at 08:29
  • As documented in Apple's [Data Formatting Guide](https://developer.apple.com/library/mac/documentation/Cocoa/Conceptual/DataFormatting/DataFormatting.html), NSDateFormatter uses the UTC date format patterns: http://www.unicode.org/reports/tr35/tr35-31/tr35-dates.html#Date_Format_Patterns . Your date format is just wrong. – Martin R May 26 '16 at 08:31
  • you need set quotes for T, like "YYYY-MM-DD'T'hh:mm:ss.s – Ravi May 26 '16 at 08:32

2 Answers2

4

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"
}
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
0
let dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.S"
if let date = dateFormatter.stringFromDate(NSDate()) {
    print(dateFormatter.stringFromDate(date) )  
}
Himali Shah
  • 181
  • 1
  • 8