Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

What's the right way to parse an ISO8601 date in cocoa?

I would like to parse ISO8601 dates in Cocoa, both for iOS 4+ and OSX 10.6+

There are a few questions about this on StackOverflow already, but in my opinion none of them contain good answers. Here's what I think constitutes a good answer:

  1. The answer should point to code with support for ISO8601. This code should compile cleanly under XCode 4 for both iOS 4+ and OSX 10.6+.

  2. The code should support all possible ISO8601 date formats.

    Please note that there are many, many possibilities here. Simply answering with one or two format strings for NSDateFormatter is not going to cut it.

  3. The answer should not be this library. That's because it is riddled with dangerous 32-bit assumptions, it's far more complicated than necessary, and it doesn't compile clean with XCode4/Clang. Bottom line: I don't trust it at all!

Thanks, fellow Cocoa-ites. I'm excited to find out if there's a real answer here!

like image 355
Dave Peck Avatar asked Jun 01 '11 00:06

Dave Peck


1 Answers

The best way is this library. ☺

I should add a link on that page to the Bitbucket repo, which contains newer source code (including 32-bit and Clang fixes!) and has an issue tracker. If you find any other bugs in it, please file them.

I'd also like to know what you mean by “more complicated than necessary”. Normal usage is very simple:

ISO8601DateFormatter *formatter = [[[ISO8601DateFormatter alloc] init] autorelease]; //Or, if you prefer, create it once in -init and own it until -dealloc 
NSDate *parsedDate = [formatter dateFromString:inString];
NSString *unparsedString = [formatter stringFromDate:inDate];

You can switch out dateFromString: or stringFromDate: for one of the longer methods if you need more information (e.g., to preserve the time zone).

If you mean something else, I want to hear it so I can improve the library.

like image 58
Peter Hosey Avatar answered Nov 14 '22 04:11

Peter Hosey