Created
November 7, 2012 18:50
-
-
Save seanwolter/4033585 to your computer and use it in GitHub Desktop.
convert a RFC3339 string to an NSDate you can use dateFromRFC3339String
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
+ (NSDate *)dateFromRFC3339String:(NSString *)dateString | |
{ | |
NSDate *date = nil; | |
if (dateString) { | |
NSDateFormatter *dateFormatter = [self internetDateTimeFormatter]; | |
NSString *RFC3339String = [[NSString stringWithString:dateString] uppercaseString]; | |
RFC3339String = [RFC3339String stringByReplacingOccurrencesOfString:@"Z" withString:@"-0000"]; | |
if (RFC3339String.length > 20) { | |
RFC3339String = [RFC3339String stringByReplacingOccurrencesOfString:@":" | |
withString:@"" | |
options:0 | |
range:NSMakeRange(20, RFC3339String.length-20)]; | |
} | |
if (!date) { // 1937-01-01T12:00:27 | |
[dateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss"]; | |
date = [dateFormatter dateFromString:RFC3339String]; | |
} | |
if (!date) { // 1996-12-19T16:39:57-0800 | |
[dateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ssZZZ"]; | |
date = [dateFormatter dateFromString:RFC3339String]; | |
} | |
if (!date) { // 1937-01-01T12:00:27.87+0020 | |
[dateFormatter setDateFormat:@"yyyy'-'MM'-'dd'T'HH':'mm':'ss.SSSZZZ"]; | |
date = [dateFormatter dateFromString:RFC3339String]; | |
} | |
if (!date) DLog(@"Could not parse RFC3339 date: \"%@\" Possible invalid format.", dateString); | |
} | |
return date; | |
} | |
+ (NSDateFormatter *)internetDateTimeFormatter | |
{ | |
NSLocale *en_US_POSIX = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; | |
NSDateFormatter *internetDateTimeFormatter = [[NSDateFormatter alloc] init]; | |
[internetDateTimeFormatter setLocale:en_US_POSIX]; | |
[internetDateTimeFormatter setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]]; | |
return internetDateTimeFormatter; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment