How to parse "MongoDB datetime (ISO Date)" to NSDate on iOS (swift and objective-c)
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
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()}
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: