Ios – Formatting month and year using NSDateFormatter returns invalid date

iosnsdateformatter

I have set the locale and timezone but when I format the date, I always get invalid date. The month is always December and year is one less that the specified year. In my case I dont need the day component.

I checked other similar post but it didn't solved the problem.

Any help is appreciated. Thank you.

Here is the code:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; 
dateFormatter.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"] autorelease]; 
dateFormatter.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"]; 
[dateFormatter setDateFormat:@"MMM YYYY"];
NSDate *formattedDate = [dateFormatter dateFromString:@"Sep 2013"];
NSLog(@"Date: %@", [dateFormatter stringFromDate:formattedDate]);
[dateFormatter release]; dateFormatter = nil;

OUTPUT: Date: Dec 2012

Best Answer

"YYYY" format is used for "Week of Year" based calendars. Use "yyyy" format specifier instead:

[dateFormatter setDateFormat:@"MMM yyyy"];
Related Topic