Processing NSDate into an ISO8601 string

xcode

 

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!