fatihyildizhan fatihyildizhan -4 years ago 152
iOS Question

How to parse "MongoDB datetime (ISO Date)" to NSDate on iOS (swift and objective-c)

How to parse "MongoDB datetime (ISO Date)" to NSDate on iOS (swift and objective-c)

This is the json result :

{
"mongodate" : "2015-06-11T14:16:56.643Z"
}


I've also answered the question.

Answer Source

Swift

  func stringToDate(date:String) -> NSDate {
  let formatter = NSDateFormatter()

  // Format 1
  formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
  if let parsedDate = formatter.dateFromString(date) {
    return parsedDate
  }

  // Format 2
  formatter.dateFormat = "yyyy-MM-dd'T'HH:mm:SSSZ"
  if let parsedDate = formatter.dateFromString(date) {
    return parsedDate
  }

  // Couldn't parsed with any format. Just get the date
  let splitedDate = date.componentsSeparatedByString("T")
  if splitedDate.count > 0 {
    formatter.dateFormat = "yyyy-MM-dd"
    if let parsedDate = formatter.dateFromString(splitedDate[0]) {
      return parsedDate
    }
  }

  // Nothing worked!
  return NSDate().toLocalTime()
}

Objective-C

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSZ"];
NSDate *date = [dateFormat dateFromString:@"2015-06-11T14:16:56.643Z"];

Formats:

// Format 1, 12Hour Style
"yyyy-MM-dd'T'HH:mm:ss.SSSZ"
2016-02-12T10:01:31.000+0000
// Format 2, 24Hour Style
"yyyy-MM-dd'T'HH:mm:SSSZ"
2016-02-12T10:01:31Z
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download