2012-04-11 64 views
2

我需要在以下日期格式在使用應用程序與美國的區域設置:1月1日,7月2日,11月28日iOS的日期格式

我應該怎麼辦呢?

NSDateFormatter搜索,但我無法設置適當的格式並且默認格式太長。

+0

這不能用NSDateFormatter的標準格式來完成。 查看此解決方案: http://stackoverflow.com/questions/1283045/ordinal-month-day-suffix-option-for-nsdateformatter-setdateformat http://stackoverflow.com/questions/3312935/nsnumberformatter-and -th-st -nd-rd-ordinal-number-endings – 2012-04-11 10:08:28

+0

看看這個:https://developer.apple.com/library/mac/#documentation/Cocoa/Conceptual/DataFormatting/Articles/dfDateFormatting10_4.html 現在的問題將是如何處理日數的普通後綴。我想你將不得不手動添加它來區分單位數... – 2012-04-11 10:09:04

+0

http://docs.oracle.com/javase/1.4.2/docs/api/java/text/SimpleDateFormat.html同樣適用於ios – dayitv89 2012-04-11 10:17:58

回答

2
NSDateFormatter *format = [[NSDateFormatter alloc] init]; 
[format setDateFormat:@"MMMM dd'st'"]; 

NSDate *now = [[NSDate alloc] init]; 

NSString *dateString = [format stringFromDate:now]; 
NSLog(@"%@",dateString); 

這會給你所需要的格式,但你需要添加一些條件,加適量「ST」,「第二」,「第三」等 like this

可能這對你有幫助

NSDateFormatter *format = [[NSDateFormatter alloc] init]; 
[format setDateFormat:@"MMMM dd"]; 

NSDate *now = [[NSDate alloc] init]; 

NSString *dateString = [format stringFromDate:[now dateByAddingTimeInterval:(-60*60*24*10)]]; 
NSMutableString *tempDate = [[NSMutableString alloc]initWithString:dateString]; 
int day = [[tempDate substringFromIndex:[tempDate length]-2] intValue]; 
switch (day) { 
    case 1: 
    **case 21: 
    case 31:** 
     [tempDate appendString:@"st"]; 
     break; 
    case 2: 
    **case 22:** 
     [tempDate appendString:@"nd"]; 
     break; 
    case 3: 
    **case 23:** 
     [tempDate appendString:@"rd"]; 
     break; 
    default: 
     [tempDate appendString:@"th"]; 
     break; 
} 
NSLog(@"%@",tempDate); 
+0

幾乎OK ,需要增加21,22和23個案例。乾杯! – cyrilPA 2012-04-12 15:50:43

+0

只看到編輯過的部分** ** – 2012-04-13 05:07:03