Skip to content

Instantly share code, notes, and snippets.

@steipete
Created March 30, 2012 21:25
Show Gist options
  • Save steipete/2255253 to your computer and use it in GitHub Desktop.
Save steipete/2255253 to your computer and use it in GitHub Desktop.
ISO 8601 parsing
+ (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];
}
@steipete
Copy link
Author

Credit where credit is due. I was messing with ISO8601DateFormatter before finding your stuff! So much simpler and better :)

@soffes
Copy link

soffes commented Mar 30, 2012

Thanks :)

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