Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How To Add Ordinal Abbreviations Format To Date In iOS e.g. "th" , "st" [duplicate]

Tags:

date

ios

nsdate

I have the following code that formats my date and time into the string like:

Monday, October 25 2013 - 14:56:34

NSDate *today = [[NSDate alloc] init];
dateFormatter = [[NSDateFormatter alloc] init];
[self.dateFormatter setDateFormat:@"EEEE, MMMM dd YYYY - HH:mm:ss"];

NSString *currentTime = [self.dateFormatter stringFromDate: today];
self.timerLabel.text = currentTime.uppercaseString;

It works well. But how do I put the "th" or "rd" or "st" appropriately unto the date i.e. after the 25 in the example above?

like image 543
motionpotion Avatar asked Feb 12 '13 19:02

motionpotion


1 Answers

NSDateFormatter *format = [[NSDateFormatter alloc] init];
[format setDateFormat:@"MMMM dd"];

NSDate *now = [[NSDate alloc] init];

NSString *dateString = [format stringFromDate:[now dateByAddingTimeInterval:(-60*60*24*10)]];
NSMutableString *tempDate = [[NSMutableString alloc]initWithString:dateString];
int day = [[tempDate substringFromIndex:[tempDate length]-2] intValue];
switch (day) {
    case 1:
    **case 21:
    case 31:**
        [tempDate appendString:@"st"];
        break;
    case 2:
    **case 22:**
        [tempDate appendString:@"nd"];
        break;
    case 3:
    **case 23:**
        [tempDate appendString:@"rd"];
        break;
    default:
        [tempDate appendString:@"th"];
        break;
}
NSLog(@"%@",tempDate);
like image 97
junaidsidhu Avatar answered Sep 28 '22 05:09

junaidsidhu