Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 939
Dr Nic Avatar asked Dec 30 '08 04:12

Dr Nic


2 Answers

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: [dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];. Not needed for iphone, or leopard as this mode is the default there.

like image 115
mfazekas Avatar answered Sep 21 '22 00:09

mfazekas


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.

like image 41
Peter Hosey Avatar answered Sep 25 '22 00:09

Peter Hosey