Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

iOS: How to get a proper Month name from a number?

Another option is to use the monthSymbols method:

int monthNumber = 11;   //November
NSDateFormatter *df = [[[NSDateFormatter alloc] init] autorelease];
NSString *monthName = [[df monthSymbols] objectAtIndex:(monthNumber-1)];

Note that you'll need to subtract 1 from your 1..12 monthNumber since monthSymbols is zero-based.


Swift 2.0

let monthName = NSDateFormatter().monthSymbols[monthNumber - 1]

Swift 4.0

let monthName = DateFormatter().monthSymbols[monthNumber - 1]

You can change the dateFormat of the NSDateFormatter. So to simplify your code:

int monthNumber = 11
NSString * dateString = [NSString stringWithFormat: @"%d", monthNumber];

NSDateFormatter* dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"MM"];
NSDate* myDate = [dateFormatter dateFromString:dateString];

[formatter setDateFormat:@"MMMM"];
NSString *stringFromDate = [formatter stringFromDate:myDate];
[dateFormatter release];

You should also set the locale once you init the date formatter.

dateFormatter.locale = [NSLocale currentLocale]; // Or any other locale

Hope this helps


Best solution for this is , standaloneMonthSymbols method,

-(NSString*)MonthNameString:(int)monthNumber
{
    NSDateFormatter *formate = [NSDateFormatter new];

    NSArray *monthNames = [formate standaloneMonthSymbols];

    NSString *monthName = [monthNames objectAtIndex:(monthNumber - 1)];

    return monthName;
}