Skip to content

Instantly share code, notes, and snippets.

@VincentMasselis
Last active January 17, 2017 13:44
Show Gist options
  • Save VincentMasselis/573ae94c3b0c6052a9f8 to your computer and use it in GitHub Desktop.
Save VincentMasselis/573ae94c3b0c6052a9f8 to your computer and use it in GitHub Desktop.
Simple Objective-C RFC3339 parser
/*
Inspired by http://cokere.com/RFC3339Date.txt
All rights deserve to Chad Okere
*/
@implementation DateUtil
+ (NSDate *)parseRFC3339Date:(NSString *)date {
NSDate *parsedDate = nil;
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSRange zRange = [date rangeOfString:@"Z"];
if (zRange.length > 0 && zRange.location == date.length - 1) {
[dateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];
parsedDate = [dateFormatter dateFromString:date];
if (parsedDate == nil) {
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSSSS'Z'"];
dateFormatter.lenient = YES;
parsedDate = [dateFormatter dateFromString:date];
}
return parsedDate;
} else {
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZZ"];
parsedDate = [dateFormatter dateFromString:date];
if (parsedDate == nil) {
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss.SSSSSSZZZZZ"];
dateFormatter.lenient = YES;
parsedDate = [dateFormatter dateFromString:date];
}
return parsedDate;
}
}
@end
@VincentMasselis
Copy link
Author

VincentMasselis commented Apr 29, 2016

Updated to handle +08:00 time zones

@VincentMasselis
Copy link
Author

VincentMasselis commented Apr 29, 2016

See test results here : http://ideone.com/B9L5PL

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment