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?
None of these answers were as aesthetically pleasing as what I'm using, so I thought I would share:
Swift 3:
Objective-C:
Obviously, this only works for English.
Here's another implementation for a method to generate the suffix. The suffixes it produces are only valid in English and may not be correct in other languages:
This will give string in format "10:10 PM Saturday, 2nd August"
The NSDateFormatter documentation says that all the format options it supports are listed in TR35.
Why do you want this? If you're making something for a machine to parse, you should use ISO 8601 format, or RFC 2822 format if you have to. Neither one of those requires or allows an ordinal suffix.
If you're showing dates to the user, you should use one of the formats from the user's locale settings.
This will do the formatting in two steps: first, create a sub-string that is the day with an appropriate suffix, then create a format string for the remaining parts, plugging in the already-formatted day.
Since the ordinal day is built by
NumberFormatter
, it should work in all languages, not just English.You could get a format string ordered for the current locale by replacing the assignment to
dateFormat
with this:Note the advice from several others that creating formatters is expensive, so you should cache and reuse them in code that is called frequently.