How to format NSDate?

偶尔善良 提交于 2019-11-26 20:46:50

问题


How can I get my NSDate to display in the format for example i.e "Tue Feb 26, 2011"


回答1:


Do it right. Don't hardcode your date formats. There are countries that are not your country and they might have different date formats. So if you want to show this date to the user you should use a method that takes the users locale into account.

You could use the dateFormatFromTemplate:options:locale: method introduced in iOS4 to get the appropriate format with all the information you want.
And if you have to support iOS < 4 you should create a plist with this template method to create the correct date format for the user locale.

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]);

gives So., 27. Feb 2011 for my locale.
and Sun, Feb 27, 2011 for the en_US locale




回答2:


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


来源:https://stackoverflow.com/questions/5131913/how-to-format-nsdate

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!