Karuppu MGR Karuppu MGR - 5 months ago 10
iOS Question

Formatting a month string is not wirking

Im trying to create a month string of type Jan,Feb,Mar. Following is my code,

-(NSString*)getMonthNameString:(int)monthNumber
{
NSDateFormatter *formate = [NSDateFormatter new];
[formate setDateFormat:@"MMM"];
NSArray *monthNames = [formate standaloneMonthSymbols];
NSString *monthName;
if (monthNumber > 0)
{
monthName = [monthNames objectAtIndex:(monthNumber - 1)];
return monthName;
}

return [monthNames objectAtIndex:1];
}


so if the month number is 1, Im expecting the code to provide month name as Jan and if it is 2, it has to provide month name as Feb and so on and so forth. But the problem is that though I have set format as
MMM
, it is still creating month of type "January", "February" etc instead of "Jan","Feb" etc...,How can I be able to sort this out?

Answer

Try:

-(NSString*)getMonthNameString:(int)monthNumber
{
    NSDateFormatter *formate = [NSDateFormatter new];
    [formate setDateFormat:@"MMM"];
    NSArray *monthNames = [formate shortMonthSymbols];
    NSString *monthName;
    if (monthNumber > 0)
    {
        monthName = [monthNames objectAtIndex:(monthNumber - 1)];
        return monthName;
    }

    return [monthNames objectAtIndex:1];
}