Matt Andersen's answer is quite complex, as is SDJMcHattie. But NSDateFormatter is pretty heavy on the processor, and if you call it 100x, you really see the effect, so here is the combined solution obtained from the answers above. (Note that the above are still true)
NSDateFormatter is insanely expensive to create. Create it once and repeatedly , but be careful: it is not thread safe, therefore, one per thread.
Assuming self.date = [NSDate date];
- (NSString *)formattedDate{ static NSDateFormatter *_dateFormatter = nil; static dispatch_once_t onceToken; dispatch_once(&onceToken, ^{ _dateFormatter = [[NSDateFormatter alloc] init]; _dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; _dateFormatter.timeZone = [NSTimeZone timeZoneForSecondsFromGMT:0]; }); _dateFormatter.dateFormat = [NSString stringWithFormat:@"h:mm a EEEE MMMM d'%@'", [self suffixForDayInDate:self.date]]; NSString *date = [_dateFormatter stringFromDate:self.date]; return date; }
/ * SDJMcHattie, this is more convenient than using an array * /
- (NSString *)suffixForDayInDate:(NSDate *)date{ NSInteger day = [[[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] components:NSDayCalendarUnit fromDate:date] day]; if (day >= 11 && day <= 13) { return @"th"; } else if (day % 10 == 1) { return @"st"; } else if (day % 10 == 2) { return @"nd"; } else if (day % 10 == 3) { return @"rd"; } else { return @"th"; } }
Exit: 15:11 Saturday, August 15
Edwin Feb 06 '14 at 11:39 2014-02-06 11:39
source share