Ordinal Month-day Suffix Option for NSDateFormatter setDateFormat

Matt Andersen picture Matt Andersen · Aug 16, 2009 · Viewed 25.6k times · Source

What setDateFormat option for NSDateFormatter do I use to get a month-day's ordinal suffix?

e.g. the snippet below currently produces:
3:11 PM Saturday August 15

What must I change to get:
3:11 PM Saturday August 15th

NSDate *date = [NSDate date];
NSDateFormatter *dateFormatter = [[[NSDateFormatter alloc] init] autorelease];
[dateFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[dateFormatter setDateFormat:@"h:mm a EEEE MMMM d"];
NSString *dateString = [dateFormatter stringFromDate:date]; 
NSLog(@"%@", dateString);

In PHP, I'd use this for the case above:
<?php echo date('h:m A l F jS') ?>

Is there an NSDateFormatter equivalent to the S option in the PHP formatting string?

Answer

cbh2000 picture cbh2000 · Apr 24, 2014

None of these answers were as aesthetically pleasing as what I'm using, so I thought I would share:


Swift 3:

func daySuffix(from date: Date) -> String {
    let calendar = Calendar.current
    let dayOfMonth = calendar.component(.day, from: date)
    switch dayOfMonth {
    case 1, 21, 31: return "st"
    case 2, 22: return "nd"
    case 3, 23: return "rd"
    default: return "th"
    }
}

Objective-C:

- (NSString *)daySuffixForDate:(NSDate *)date {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSInteger dayOfMonth = [calendar component:NSCalendarUnitDay fromDate:date];
    switch (dayOfMonth) {
        case 1:
        case 21:
        case 31: return @"st";
        case 2:
        case 22: return @"nd";
        case 3:
        case 23: return @"rd";
        default: return @"th";
    }
}

Obviously, this only works for English.