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

前端 未结 11 814
一向
一向 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:20

    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

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

    How about:

    NSUInteger i = <your month integer>;
    NSDateFormatter *df = [NSDateFormatter new];
    // change locale if the standard is not what you want
    NSArray *monthNames = [df standaloneMonthSymbols];
    NSString *monthName = [monthNames objectAtIndex:(i - 1)];
    [df release];
    
    0 讨论(0)
  • 2020-11-30 23:21

    NSDate to NSString -> As Dateformat Ex: 2015/06/24

            NSDateFormatter *dateformate=[[NSDateFormatter alloc]init];
            [dateformate setDateFormat: @"yyyy/MM/dd"];
            NSString *date = [dateformate stringFromDate:selectedDate]; // Convert date to string
    

    NSDate to NSString -> As Dateformat Ex: 2015 June 24, 1:02 PM

            [dateformate setDateFormat:@"yyyy MMMM dd, h:mm a"];
            NSString *displayDate = [dateformate stringFromDate:selectedDate]; // Convert date to string
            NSLog(@"date :%@",date);
            NSLog(@"Display time = %@", displayDate);
    
    0 讨论(0)
  • 2020-11-30 23:25

    You should be able to get rid of the release and re-allocation of the dateFormatter, cutting out a couple of lines, but that's all I see.

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

    Swift 4.X

    print((DateFormatter().monthSymbols[month-1].capitalized)) //month is int less than 12

    For Example:

    print((DateFormatter().monthSymbols[11-1].capitalized))

    Output

    November

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

    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;
    }
    
    0 讨论(0)
提交回复
热议问题