HI,
我需要在iPhone SDK中显示日期为“2010年11月15日”。
我该怎么做?
谢谢!
答案 0 :(得分:1)
您可以按照this post:
中的说明使用日期格式化程序// Given some NSDate* date
NSDateFormatter* formatter = [[[NSDateFormatter alloc] init] autorelease];
[formatter setDateFormat:@"dd MMM yyyy"];
NSString* formattedDate = [formatter stringFromDate:date];
我相信你只需将“th”放在格式字符串中dd的末尾即可。像这样:
@"ddth MMM yyy
但我没有在我面前测试我的Mac。如果这不起作用,你可以尝试这样的事情:
[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 :(得分:1)
我知道我正在回答一些旧事;但我做了以下事情。
@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 and 'th' 'st' 'nd' 'rd' (ordinal) number endings