2011-02-27 50 views
4

我怎樣才能讓我的NSDate在格式例如顯示即「星期二2011年2月26日」如何格式化NSDate?

+0

關於[NSDate格式化](http://stackoverflow.com/search?q=nsdate+format)這裏已經有很多問題了,它們都不適合你嗎? – zoul

回答

33

這樣做的權利。 請勿硬編碼您的日期格式。有些國家不是您的國家,他們可能有不同的日期格式。所以,如果你想向用戶顯示這個日期,你應該使用一個方法來考慮用戶的語言環境。

您可以使用iOS4中引入的dateFormatFromTemplate:options:locale:方法來獲取所需的所有信息的相應格式。
如果您必須支持iOS < 4,則應該使用此模板方法創建一個plist,以便爲用戶區域設置創建正確的日期格式。

NSLocale *locale = [NSLocale currentLocale]; 
NSDateFormatter *formatter = [[[NSDateFormatter alloc] init] autorelease]; 
NSString *dateFormat = [NSDateFormatter dateFormatFromTemplate:@"E MMM d yyyy" options:0 locale:locale]; 
[formatter setDateFormat:dateFormat]; 
[formatter setLocale:locale]; 
NSLog(@"Formatted date: %@", [formatter stringFromDate:myDate]); 

給出我的區域設置的So., 27. Feb 2011
Sun, Feb 27, 2011 en_US區域設置

+3

聽起來像某人總是看到美國的格式化日期;) – Jeff

+0

你救了我的一天男人 –

2
NSDateFormatter *gmtFormatter = [[NSDateFormatter alloc] init]; 
[gmtFormatter setDateFormat:@"E MMM d yyyy"];