Jayson Lane
Jayson Lane

Reputation: 2828

NSDate Conversion

I'm attempting to convert a date from MMM dd, YYYY to YYYY-MM-dd.

    NSDateFormatter *importDateFormat = [[NSDateFormatter alloc] init];
    [importDateFormat setDateFormat:@"MMM dd, YYYY"];

    NSDate *importedDate = [importDateFormat dateFromString:expiresOn.text];

    NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
    [dateFormat setDateFormat:@"YYYY-MM-dd"];

    NSString *dateImported = [dateFormat stringFromDate:importedDate];

The date brought in from the expiresOn.text (label) is: Oct 08, 2012

The date contained in dateImported after conversion is: 2011-12-25

Am I missing something? Is there something wrong with my date formatter?

Upvotes: 0

Views: 335

Answers (1)

rckoenes
rckoenes

Reputation: 69469

Well there are two things wrong, first is yyyy not YYYYY and since you are parsing the month as a word you need to tell the date formatter which language to expect.

NSDateFormatter *importDateFormat = [[NSDateFormatter alloc] init];
[importDateFormat setDateFormat:@"MMM dd, yyyy"];
importDateFormat.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en"] autorelease];

NSDate *importedDate = [importDateFormat dateFromString:expiresOn.text];

NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; 
[dateFormat setDateFormat:@"yyyy-MM-dd"];

NSString *dateImported = [dateFormat stringFromDate:importedDate];

If you are using ARC, then remove the autorelease part in the NSLocale; if you are not using ARC, you need to release the NSDateFormatter.

Upvotes: 3

Related Questions