2

I need to have the following date formatted while using the application with an US locale: January 1st, July 2nd, November 28th

How should I do that?

Searched with NSDateFormatter, but I'm not able to set an appropriate format and default formats are too long.

Cœur
  • 37,241
  • 25
  • 195
  • 267
cyrilPA
  • 269
  • 1
  • 2
  • 14
  • This cannot be done using standart formats of NSDateFormatter. See this solutions: http://stackoverflow.com/questions/1283045/ordinal-month-day-suffix-option-for-nsdateformatter-setdateformat http://stackoverflow.com/questions/3312935/nsnumberformatter-and-th-st-nd-rd-ordinal-number-endings – Evgeny Aleksandrov Apr 11 '12 at 10:08
  • Take a look at this: https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html The problem now will be how to handle the ordinary suffix for day number. I guess you will have to add it manually distinguishing the units number... – Ricard Pérez del Campo Apr 11 '12 at 10:09
  • http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html same for ios – gauravds Apr 11 '12 at 10:17

1 Answers1

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

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

NSString *dateString = [format stringFromDate:now];
NSLog(@"%@",dateString);

this will give you the required format but you need to add some condition to add proper 'st','nd','rd' etc. like this

might this be helpful to you

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);
Community
  • 1
  • 1
The iOSDev
  • 5,237
  • 7
  • 41
  • 78