开发者

Date formatter for converting 14-sept-2011 in 14th Sept

I have a string 14-Sep-2011 In need to convert this 14th Sept. This date may be any date string. Is there any date formatter which allows me to convert date in my format. As if date is 1-Sept-2011 then I need 1st Sept, 2-Sept-2011 should say 2nd Sept.

Can anyone please 开发者_StackOverflowsuggest the solution.

Thanks


- (NSString *)ordinalSuffixFromInt:(int)number {
    NSArray *cSfx = [NSArray arrayWithObjects:@"th", @"st", @"nd", @"rd", @"th", @"th", @"th", @"th", @"th", @"th", nil];
    NSString *suffix = @"th";

    number = abs(number % 100);
    if ((number < 10) || (number > 19)) {
        suffix = [cSfx objectAtIndex:number % 10];
    }
    return suffix;
}

Test:

- (void)test {
    for (int day=1; day<=31; day++) {
        NSLog(@"ordinal: %d%@", day, [self ordinalSuffixFromInt:day]);
    }
}


You try the following code because I run successfully.

    NSString *dateStr = @"14-Sep-2011";
    NSDateFormatter *dtF = [[NSDateFormatter alloc] init];
    [dtF setDateFormat:@"dd-MMM-yyyy"];
    NSDate *d = [dtF dateFromString:dateStr];
    NSDateFormatter *monthDayFormatter = [[[NSDateFormatter alloc] init] autorelease];
    [monthDayFormatter setFormatterBehavior:NSDateFormatterBehaviorDefault];
    [monthDayFormatter setDateFormat:@"d MMM"];         
    int date_day = [[monthDayFormatter stringFromDate:d] intValue];      
    NSString *suffix_string = @"|st|nd|rd|th|th|th|th|th|th|th|th|th|th|th|th|th|th|th|th|th|st|nd|rd|th|th|th|th|th|th|th|st";
    NSArray *suffixes = [suffix_string componentsSeparatedByString: @"|"];
    NSString *suffix = [suffixes objectAtIndex:date_day];   
    NSString *format = [NSString stringWithFormat:@"%d",date_day];
    NSString *dateStrfff = [format stringByAppendingString:suffix];
    NSLog(@"%@", dateStrfff);
    [monthDayFormatter setDateFormat:@"MMM"];
    NSString *ss = [monthDayFormatter stringFromDate:d];
    NSLog(@"%@",ss);

    NSString *final = [dateStrfff stringByAppendingString:ss];
    NSLog(@"final string:---> %@",final);

This is a perfect solution that you want.


This will work for any number :

 -(NSString *) ordinalSuffix: (NSInteger) day {
    NSString *ordinalSuffix;

    if(day%10 == 1 && day%100 != 11) ordinalSuffix = @"st";
    else if(day%10 == 2 && day%100 != 12) ordinalSuffix = @"nd";
    else if(day%10 == 3 && day%100 != 13) ordinalSuffix = @"rd";
    else ordinalSuffix = @"th";

    return ordinalSuffix;
 }

Test :

 -(void) test {
     for(NSInteger i = 1; i < 200; i++)
         NSLog(@"%d%@", i, [self ordinalSuffix:i]);
 }


use it

     NSString *string =@"14-Sep-2011";
    NSArray *arr = [string componentsSeparatedByString:@"-"];
    NSString *str1=[arr objectAtIndex:0];
    str1=[str1 stringByAppendingString:@"th"];
    NSString *final=[str1 stringByAppendingFormat:@" %@",[arr objectAtIndex:1]];
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜