views:

2272

answers:

3

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.

+2  A: 

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.

Peter Hosey
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.
Bob Aman
A: 

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.

Arclite
Please don't use this, NSCalendarDate has been deprecated for a while and probably won't be around after (by even?) Snow Leopard.
Ashley Clark
+16  A: 

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.

mfazekas
+1 for adding unicode date format patterns link. Been looking for something like that for a while.
rein
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'"];
Kaom Te