Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 291
fatihyildizhan Avatar asked Jun 12 '15 09:06

fatihyildizhan


3 Answers

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
like image 88
fatihyildizhan Avatar answered Nov 20 '22 19:11

fatihyildizhan


Swift 3 update of @fatihyildizhan's answer:

func stringToDate(date: String) -> Date {
    let formatter = DateFormatter()

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

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

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

    // Nothing worked!
    return Date()
}
like image 44
user3344977 Avatar answered Nov 20 '22 20:11

user3344977


As of iOS 10+, there is now an ISO8601DateFormatter.

https://developer.apple.com/reference/foundation/iso8601dateformatter

HOWEVER ... it doesn't handle the decimal seconds that you sometimes get from MongoDB date strings, here's a simple work-around:

ISO8601DateFormatter doesn't parse ISO date string

like image 2
Greg Anderson Avatar answered Nov 20 '22 20:11

Greg Anderson