Processing NSDate into an ISO8601 string
During the CSCW Lab, where I had the experience of working on iPhone, I had to connect to a XML RPC server. Some of the parameters of the request had to be formatted as ISO8601 standard. After some reading, I end up using the following code, managing both the conversion of a NSDate to NSString and a NSString to a NSDATE using the above format:
NSString –> NSDate
-(NSString *) strFromISO8601:(NSDate *) date {
static NSDateFormatter* sISO8601 = nil;
if (!sISO8601) {
sISO8601 = [[NSDateFormatter alloc] init];
NSTimeZone *timeZone = [NSTimeZone localTimeZone];
int offset = [timeZone secondsFromGMT];
NSMutableString *strFormat = [NSMutableString stringWithString:@"yyyyMMdd'T'HH:mm:ss"];
offset /= 60; //bring down to minutes
if (offset == 0)
[strFormat appendString:ISO_TIMEZONE_UTC_FORMAT];
else
[strFormat appendFormat:ISO_TIMEZONE_OFFSET_FORMAT, offset / 60, offset % 60];
[sISO8601 setTimeStyle:NSDateFormatterFullStyle];
[sISO8601 setDateFormat:strFormat];
}
return[sISO8601 stringFromDate:date];
}
NSDate –> NSString^
-(NSDate *) dateFromISO8601:(NSString *) str {
static NSDateFormatter* sISO8601 = nil;
if (! sISO8601) {
sISO8601 = [[NSDateFormatter alloc] init];
[sISO8601 setTimeStyle:NSDateFormatterFullStyle];
[sISO8601 setDateFormat:@"yyyyMMdd'T'HH:mm:ss"];
}
if ([str hasSuffix:@"Z"]) {
str = [str substringToIndex:(str.length-1)];
}
NSDate *d = [sISO8601 dateFromString:str];
return d;
}
Enjoy!














What are the values of “ISO_TIMEZONE_UTC_FORMAT” and “ISO_TIMEZONE_OFFSET_FORMAT” ?
Could to speak to the logic behind the “offset” value and what is going on when it equal to 0 versus !=0?
Could you post the complete class these methods belong to?
Thanks! Great post.