Monday, March 7, 2011

Parsing unsupported date formats in via Cocoa's NSDate

With the Cocoa framework how can I parse @"2008-12-29T00:27:42-08:00" into an NSDate object? The standard -dateWithString: doesn't like it.

From stackoverflow
  • If you only need to handle the ISO 8601 format (of which that string is an example), you might try my ISO 8601 parser and unparser.

    Bob Aman : Maybe if the code were licensed with MIT or Apache 2.0. BSD sucks for use with iPhone apps because of the attribution clause, since most apps don't actually distribute documentation with the binary.
  • You'll need to look at NS**Calendar**Date's initWithString:calendarFormat: to handle custom date strings. Look at page 16 and 17 of this document to find the correct format specifiers.

    Ashley Clark : Please don't use this, NSCalendarDate has been deprecated for a while and probably won't be around after (by even?) Snow Leopard.
  • You can use NSDateFormatter to parse dates:

        NSDateFormatter* dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
        [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];
        date = [dateFormatter dateFromString:dateStr];
    

    The unicode date format patterns defines the format string you can use with the setDateFormat: method.

    Note that if you're targeting 10.4 then you need to call: [dateFromatter setFormatterBehavior:NSDateFormatterBehavior10_4];. Not needed for iphone, or leopard as this mode is the default there.

    rein : +1 for adding unicode date format patterns link. Been looking for something like that for a while.
    Kaom Te : I couldn't get this to work unless I quoted the Z as well like so [dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ss'Z'"];

0 comments:

Post a Comment