How to display the date as “November 15, 2010” in the iPhone SDK?

Hi

I need to display the date as "November 15, 2010" in the iPhone SDK.

How to do it?

Thank!

+3
source share
2 answers

You can use date formatting as described in this post :

// Given some NSDate* date
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:@"dd MMM yyyy"];
NSString* formattedDate = [formatter stringFromDate:date];

I believe that you can just put "th" at the end of dd in the format string. eg:

@"ddth MMM yyy

but I don’t have my Mac in front of me to check it out. If this does not work, you can try something like this:

[formatter setDateFormat:@"dd"];
NSString* day = [formatter stringFromDate:date];
[formatter setDateFormat:@"MMM yyyy"];
NSString* monthAndYear = [formatter stringFromDate:date];
NSString* date = [NSString stringWithFormat:@"%@th %@", day, monthAndYear];
+1
source

I know that I am responding to something old; but I did the following.

@implementation myClass
    + (NSString *) dayOfTheMonthToday
        {
         NSDateFormatter *DayFormatter=[[NSDateFormatter alloc] init];
         [DayFormatter setDateFormat:@"dd"];
         NSString *dayString = [DayFormatter stringFromDate:[NSDate date]];
          //yes, I know I could combined these two lines - I just don't like all that nesting
         NSString *dayStringwithsuffix = [myClass buildRankString:[NSNumber numberWithInt:[dayString integerValue]]];

         NSLog (@"Today is the %@ day of the month", dayStringwithsuffix);
    }

+ (NSString *)buildRankString:(NSNumber *)rank
{
    NSString *suffix = nil;
    int rankInt = [rank intValue];
    int ones = rankInt % 10;
    int tens = floor(rankInt / 10);
    tens = tens % 10;
    if (tens == 1) {
        suffix = @"th";
    } else {
        switch (ones) {
            case 1 : suffix = @"st"; break;
            case 2 : suffix = @"nd"; break;
            case 3 : suffix = @"rd"; break;
            default : suffix = @"th";
        }
    }
    NSString *rankString = [NSString stringWithFormat:@"%@%@", rank, suffix];
    return rankString;
}
@end

: NSNumberFormatter 'th' 'st' 'nd' 'rd' ()

+1

Source: https://habr.com/ru/post/1774868/


All Articles