Convert string to date in my iPhone app

AppAspect picture AppAspect · Dec 7, 2010 · Viewed 90k times · Source

I have made a calendar application for the iPhone in which I have a date in string format (e.g. "Tue, 25 May 2010 12:53:58 +0000").

I want to convert this to an NSDate.

What do I need to use to do that?

Answer

Sam Ritchie picture Sam Ritchie · Dec 7, 2010

Take a look at the class reference for NSDateFormatter. You use it like this:

NSString *dateStr = @"Tue, 25 May 2010 12:53:58 +0000";

// Convert string to date object
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"EE, d LLLL yyyy HH:mm:ss Z"];
NSDate *date = [dateFormat dateFromString:dateStr]; 
[dateFormat release];

For more information on how to customize that NSDateFormatter, try this reference guide.

EDIT:

Just so you know, this is going to parse the full month name. If you want three letter month names, use LLL instead of LLLL.