-1

I'm trying to convert String to NSDate with this code

let dateString = data as! String
let formatter = DateFormatter()
formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
let date = formatter.date(from: dateString)
let Calendar = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)
let unitFlags: NSCalendar.Unit = [.hour, .day, .month, .year]
let components = Calendar?.components(unitFlags, from: date!)

and dateString is "2017-04-03T18:50:34.3042751+04:30" but I'm getting fatal error: unexpectedly found nil while unwrapping an Optional value for the last line. What am I doing wrong?

Amir_P
  • 8,322
  • 5
  • 43
  • 92

1 Answers1

0

Change your date format as below

formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SZ"

Edit: If you want more precision the you can add two more S e.g.

formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"

S will work upto 3 times after that it won't work. If you need to parse fractional seconds after 3 decimal places then you need to see this thread : https://stackoverflow.com/a/27412262/468724

Community
  • 1
  • 1
Inder Kumar Rathore
  • 39,458
  • 17
  • 135
  • 184