Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Formatting month and year using NSDateFormatter returns invalid date

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

like image 768
Nibin V Avatar asked Apr 10 '12 06:04

Nibin V


1 Answers

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

[dateFormatter setDateFormat:@"MMM yyyy"];
like image 175
Vladimir Avatar answered Sep 23 '22 23:09

Vladimir