Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

NSDateFormatter not showing full month name, only single digit number

Not sure what the issue is, but instead of getting a month name "July", I get "07".

dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setLocale:[NSLocale systemLocale]];
[dateFormat setTimeZone:[NSTimeZone localTimeZone]];    
[dateFormat setDateFormat:@"MMMM dd, h:mm a"];

I have tried M, MM, MMM, MMMM, and all of them give me a number, instead of the month name, though with different amounts of leading 0s.

like image 678
Chris Avatar asked Aug 24 '12 19:08

Chris


3 Answers

Turns out to be an issue with the second line, setLocale. I assume that the system won't default to using english month names when the locale has been manually set? I live in an english speaking locale, but maybe it doesn't matter.

In any case, not setting the locale fixes the month name issue.

dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setTimeZone:[NSTimeZone localTimeZone]];    
[dateFormat setDateFormat:@"MMMM dd, h:mm a"];
like image 131
Chris Avatar answered Nov 17 '22 00:11

Chris


The problem is the locale, not the format. Check this out:

http://waracle.net/mobile/iphone-nsdateformatter-date-formatting-table/

Basically, "MMMM" will give you the full name for the month.

like image 31
J2theC Avatar answered Nov 17 '22 00:11

J2theC


-systemLocale is not what you want here. It returns a fallback locale if no other locale fits. Use -currentLocale to get the user's current locale.

Also:
You should use NSDateFormatter's +dateFormatFromTemplate:options:locale: method to get the correct date format. In some languages the day comes before the month, etc. and vice versa.

like image 8
Fabian Kreiser Avatar answered Nov 17 '22 00:11

Fabian Kreiser