0

"2015-06-30T17:30:36.000Z" is an example of DateTime value in MySQL. How to convert it to NSDate in Swift?

Below is my code but it does not work

var sqlDateFormatter = NSDateFormatter()
sqlDateFormatter.dateFormat = "yyyy’-‘MM’-'dd’T'HH’:'mm’:'ss'Z’"
self.whenPublished = self.sqlDateFormatter.dateFromString("2015-06-30T17:30:36.000Z")
Dustin Sun
  • 5,292
  • 9
  • 49
  • 87

1 Answers1

11

You just need to add the milliseconds thats it is missing at the end of your dateFormat string. Try like this:

let dateFormatter = DateFormatter()
dateFormatter.calendar = Calendar(identifier: .iso8601)
dateFormatter.locale = Locale(identifier: "en_US_POSIX")
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
let string = "2015-06-30T17:30:36.000Z"
if let date = dateFormatter.date(from: string) {
    print(date)   // "2015-06-30 17:30:36 +0000"
}

Note: You need to use regular single cote ' instead of curved cote

Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
  • this link may be helpful: https://stackoverflow.com/questions/35700281/date-format-in-swift/52297497#52297497 – BatyrCan Dec 01 '18 at 21:21