Based on @JeffCompton 's suggestion I ended up doing this:
+ (NSDate *)dateFromISO8601:(NSString *)dateString {
if (!dateString) return nil;
if ([dateString hasSuffix:@"Z"]) {
dateString = [[dateString substringToIndex:(dateString.length - 1)] stringByAppendingString:@"-0000"];
}
NSString *cleanDateString = dateString;
NSArray *dateComponents = [dateString componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"."]];
if ([dateComponents count] > 1){
NSArray *timezoneComponents = [[dateComponents objectAtIndex:1] componentsSeparatedByCharactersInSet:[NSCharacterSet characterSetWithCharactersInString:@"-"]];
if ([timezoneComponents count] > 1){
cleanDateString = [NSString stringWithFormat:@"%@-%@", [dateComponents objectAtIndex:0], [timezoneComponents objectAtIndex:1]];
}
}
dateString = [cleanDateString stringByReplacingOccurrencesOfString:@":" withString:@""];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = @"yyyy-MM-d'T'HHmmssZZZ";
NSDate *resultDate = [dateFormatter dateFromString:dateString];
return resultDate;
}
This is a modification of some open-source code but I lost the reference to the original code.
The reason for all the modifications is that I am connecting to API's that can give me the date with decimals or without, and sometimes without the : separating HH, mm, and ss.