Raphael Caixeta
Raphael Caixeta

Reputation: 7846

Proper way to convert NSString to NSDate on iOS?

I've been using this method to convert a regular NSString object to an NSDate, but tried submitting an update to Apple and it was denied. What's another way to do this in iOS?

NSString *date_str = @"2011-08-12T12:20:00Z";
NSDate *the_date = [NSDate dateWithNaturalLanguageString:date_str locale:[[NSUserDefaults standardUserDefaults] dictionaryRepresentation]];

Thanks in advance!

Upvotes: 3

Views: 4561

Answers (1)

Mac
Mac

Reputation: 14791

Use an NSDateFormatter. Brief example follows:

...
NSString* dateString = "2011-08-12T12:20:00Z";
NSDateFormatter* fmt = [NSDateFormatter new];
[fmt setDateFormat:"yyyy-MM-dd'T'HH:mm:ss'Z'"];
NSDate* date = [fmt dateFromString:dateString];
[fmt release];
...

Note that as per Unicode Technical Standard #35, NSDateFormatter doesn't natively support single-letter time-zone identifiers (i.e. Z for zulu time).

Upvotes: 9

Related Questions