What is the correct way to parse an ISO8601 date in cocoa?

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

There are a few questions about StackOverflow about this, but in my opinion none of them contain good answers. Here is what I consider a good answer:

  • The response should point to code that supports ISO8601. This code should easily compile under Xcode 4 for iOS 4+ and OSX 10.6 +.

  • The code must support all possible ISO8601 date formats.

    Please note that there are many, many opportunities. Just an answer with one or two lines of format for NSDateFormatter will not shorten it.

  • The answer should not be this library . This is because it is riddled with dangerous 32-bit assumptions, it is much more complicated than necessary, and it does not compile with Xcode4 / Clang. Bottom line: I do not believe at all!

Thanks, friend Cocoa -ites. I am glad to know if there is a real answer here!

+7
source share
1 answer

The best way is this library . ☺

I have to add the link to this page to the Bitbucket repository , which contains the newer source code (including 32-bit and Clang fixes!) And there is an error tracker. If you find any other errors in it, write them.

I would also like to know what you mean by "more complex than necessary." Normal use 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 disable dateFromString: or stringFromDate: for one of the longer methods if you need additional information (for example, to save the time zone).

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

+6
source