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

前端 未结 11 815
一向
一向 2020-11-30 22:43

I know that the NSDateformatter suite of functionality is a boon for mankind, but at the same time it is very confusing to me. I hope you can help me out.

Somewhere

相关标签:
11条回答
  • 2020-11-30 23:36

    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.

    0 讨论(0)
  • 2020-11-30 23:37

    Both answers from Anna Karenina and Carl doesn't work that well as they won't return month name in nominativ for some cultures. I suggest to use the proposed solution from Pascal, which solves this issue (by replacing monthSymbols with standaloneMonthSymbols)

    0 讨论(0)
  • 2020-11-30 23:37

    In Swift 3.0

        let monthNumber = 3
        let fmt = DateFormatter()
        fmt.dateFormat = "MM"
        let month = fmt.monthSymbols[monthNumber - 1]
        print(month)
    
        // result
       "March\n"        
    
    0 讨论(0)
  • 2020-11-30 23:38

    And with ARC :

    + (NSString *)monthNameFromDate:(NSDate *)date {
        if (!date) return @"n/a";
        NSDateFormatter *df = [[NSDateFormatter alloc] init];
        [df setDateFormat:@"MM"];
        return [[df monthSymbols] objectAtIndex:([[df stringFromDate:date] integerValue] - 1)];
    }
    
    0 讨论(0)
  • 2020-11-30 23:42

    Swift 2.0

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

    Swift 4.0

    let monthName = DateFormatter().monthSymbols[monthNumber - 1]
    
    0 讨论(0)
提交回复
热议问题