我有一些像这样的代码:
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];
[df2 setDateFormat:@"MMMM d YYYY"];
NSString *s = [df2 stringFromDate:date1];
NSLog(@"my new Date is %@",s);
//Output : March 23 2013
但我想这样:2013年3月23日,如何解决?
答案 0 :(得分:3)
使用:
[df2 setDateFormat:@"MMMM d'rd' YYYY"];
* 注意,对于21,22,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);
注意:我使用了switch,你可以使用数组重构它。
现在你可以
答案 1 :(得分:1)
直接在IOS中不可用,但我使用以下代码
实现了它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];
[df2 setDateFormat:@"MMMM d YYYY"];
NSString *s = [df2 stringFromDate:date1];
NSDateFormatter *monthDayFormatter = [[NSDateFormatter alloc] init];
[monthDayFormatter setFormatterBehavior:NSDateFormatterBehavior10_4];
[monthDayFormatter setDateFormat:@"d"];
int date_day = [[monthDayFormatter stringFromDate:date1] 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];
NSLog(@"Suffix %@",suffix);