Created
March 30, 2012 21:25
-
-
Save steipete/2255253 to your computer and use it in GitHub Desktop.
ISO 8601 parsing
This file contains 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 *)dateFromISO8601String:(NSString *)iso8601 { | |
if (!iso8601) { | |
return nil; | |
} | |
const char *str = [iso8601 cStringUsingEncoding:NSUTF8StringEncoding]; | |
char newStr[24]; | |
struct tm tm; | |
size_t len = strlen(str); | |
if (len == 0) { | |
return nil; | |
} | |
// UTC | |
if (len == 20 && str[len - 1] == 'Z') { | |
strncpy(newStr, str, len - 1); | |
strncpy(newStr + len - 1, "+0000\0", 6); | |
} | |
// Timezone | |
else if (len == 24 && str[22] == ':') { | |
strncpy(newStr, str, 22); | |
strncpy(newStr + 22, str + 23, 2); | |
} | |
// Poorly formatted timezone | |
else { | |
strncpy(newStr, str, len > 24 ? 24 : len); | |
} | |
if (strptime(newStr, "%FT%T%z", &tm) == NULL) { | |
return nil; | |
} | |
time_t t; | |
t = mktime(&tm); | |
return [NSDate dateWithTimeIntervalSince1970:t]; | |
} | |
- (NSString *)ISO8601String { | |
struct tm *timeinfo; | |
char buffer[80]; | |
time_t rawtime = (time_t)[self timeIntervalSince1970]; | |
timeinfo = gmtime(&rawtime); | |
strftime(buffer, 80, "%Y-%m-%dT%H:%M:%SZ", timeinfo); | |
return [NSString stringWithCString:buffer encoding:NSUTF8StringEncoding]; | |
} |
Credit where credit is due. I was messing with ISO8601DateFormatter before finding your stuff! So much simpler and better :)
Thanks :)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This looks familiar :)