Formatting the month and year using NSDateFormatter returns an invalid date

I set the locale and timezone, but when I format the date, I always get an invalid date. The month is always December, and the year is less than the specified year. In my case, I do not need the component of the day.

I checked another similar message, but this did not solve the problem.

Any help is appreciated. Thanks.

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: December 2012

+8
ios nsdateformatter
source share
2 answers

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

 [dateFormatter setDateFormat:@"MMM yyyy"]; 
+15
source share

I just wanted to add something to Vladimir’s great answer. If you do this before setting your own language, it seems that date formatting is going crazy. I needed to set the locale before setting up a new format, and then use setDateFormat to change the format depending on the locale used. So something like this:

 NSDateFormatter *formatter = [[NSDateFormatter alloc] init]; [formatter setLocale:[NSLocale currentLocale]];//I wanted to set the locale to wherever user is using my app in [formatter setDateFormat:@"MMM YYYY"]; NSDate *now = [NSDate Date]; NSString *fancyLookingDate = [formatter stringFromDate:now]; 
0
source share

All Articles