NSNumberFormatter and 'th' 'st' 'nd' 'rd' (ordinal) number endings

前端 未结 20 1225
粉色の甜心
粉色の甜心 2020-12-03 00:38

Is there a way to use NSNumberFormatter to get the \'th\' \'st\' \'nd\' \'rd\' number endings?

EDIT:

Looks like it does not exist. Here\'s what I\'m using.

20条回答
  •  自闭症患者
    2020-12-03 01:17

    This will convert date to string and also add ordinal in the date. You can modify the date formatte by changing NSDateFormatter object

    -(NSString*) getOrdinalDateString:(NSDate*)date
    {
        NSString* string=@"";
        NSDateComponents *components = [[NSCalendar currentCalendar] components: NSCalendarUnitDay fromDate:date];
    
        if(components.day == 1 || components.day == 21 || components.day == 31)
            string = @"st";
    
        else if (components.day == 2 || components.day == 22)
            string = @"nd";
    
        else if (components.day == 3 || components.day == 23)
            string = @"rd";
    
        else
            string = @"th";
    
    
        NSDateFormatter *dateFormatte = [[NSDateFormatter alloc] init];
        [dateFormatte setFormatterBehavior:NSDateFormatterBehavior10_4];
        [dateFormatte setDateFormat:[NSString stringWithFormat:@"d'%@' MMMM yyyy",string]];
    
        NSString *dateString = [dateFormatte stringFromDate:date];
        return dateString;
    }
    

提交回复
热议问题