Jack Humphries
Jack Humphries

Reputation: 13267

Convert NSString back to NSDate

I am using NSDateFormatter to convert the current date to a string (in the format: February 16, 2013). How can I convert this string back to a NSDate object?

NSString *dateString = [NSDateFormatter localizedStringFromDate:[NSDate date] dateStyle:NSDateFormatterLongStyle timeStyle:NSDateFormatterNoStyle];

The problem appears to be that the month is written out (February vs. 02), and other questions only explain to use NSDateFormatter with a format such as MM-dd-yyyy, which I do not believe is possible here. Must I parse this date manually, convert February to 02, and go from there?

Upvotes: 1

Views: 661

Answers (3)

rmaddy
rmaddy

Reputation: 318814

Since you have a fixed format that you wish to parse, you must setup the date formatter with the locale of en_US_POSIX. Then you must set he date format to MMMM dd, yyyy. This will pare any date string that has the full month name, the month day, a comma, then the four-digit year.

Upvotes: 1

vikingosegundo
vikingosegundo

Reputation: 52227

If you want to be able to use localized date formats, you should go with templates

 NSString *dateString = [NSDateFormatter localizedStringFromDate:[NSDate date]
                                                       dateStyle:NSDateFormatterLongStyle
                                                       timeStyle:NSDateFormatterNoStyle];

NSLog(@"%@", dateString);

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];    
[dateFormatter setDateFormat:[NSDateFormatter dateFormatFromTemplate:@"MMMdY"
                                                             options:0
                                                              locale:[NSLocale currentLocale]]];

NSLog(@"%@", [dateFormatter dateFromString:dateString]);

Upvotes: 1

Nikita Leonov
Nikita Leonov

Reputation: 5694

You can use dateFromString of the same NSDateFormatter class to perform backward conversion. To make it work you need to define dateStyle, so parser will know how text string should be parsed. For the date style that you provided code below will work:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateStyle:NSDateFormatterLongStyle];
NSDate *date = [dateFormatter dateFromString:@"February 16, 2013"];

NSLog(@"%@", date);

Upvotes: 4

Related Questions