利用:
[df2 setDateFormat:@"MMMM d'rd' YYYY"];
*注意,对于 21st, 22nd, rd, th 等,您需要检查使用条件,然后更改格式化程序
NSString *dateStr = @"23 03 2013";
NSDateFormatter *df1 = [[NSDateFormatter alloc] init];
[df1 setDateFormat:@"d MM yyyy"];
NSDate *date1 = [df1 dateFromString:dateStr];
NSDateFormatter *df2 = [[NSDateFormatter alloc] init];
NSDateFormatter *dfDate=[NSDateFormatter new];
[dfDate setDateFormat:@"dd"];
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:NSMonthCalendarUnit|NSDayCalendarUnit fromDate:date1];
NSInteger dayValue=[components day];
/*
switch (dayValue) {
case 1:
case 21:
case 31:
[df2 setDateFormat:@"MMMM d'st' YYYY"];
break;
case 2:
case 22:
[df2 setDateFormat:@"MMMM d'nd' YYYY"];
break;
case 3:
case 23:
[df2 setDateFormat:@"MMMM d'rd' YYYY"];
break;
case 4:
case 5:
case 6:
case 7:
case 8:
case 9:
case 10:
case 11:
case 12:
case 13:
case 14:
case 15:
case 16:
case 17:
case 18:
case 19:
case 20:
case 24:
case 25:
case 26:
case 27:
case 28:
case 29:
case 30:
[df2 setDateFormat:@"MMMM d'th' YYYY"];
break;
default:
break;
}
*/
NSArray *suffix=@[@"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"];
NSLog(@"%d",[suffix count]);
[df2 setDateFormat:[NSString stringWithFormat:@"MMMM d'%@' YYYY",suffix[dayValue - 1]]];
NSString *s = [df2 stringFromDate:date1];
NSLog(@"my new Date is %@",s);
注意:我使用了开关,您可以使用数组对其进行重构。
现在你可以