且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何格式化NSDate?

更新时间:2023-10-03 23:37:16

对的。 请勿对日期格式进行硬编码。有些国家/地区不是您所在的国家/地区,可能会有不同的日期格式。因此,如果要向用户显示此日期,则应使用将用户区域设置考虑在内的方法。

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.

您可以使用 dateFormatFromTemplate :options:locale:在iOS4中引入的方法,以获得所需的所有信息的适当格式。

如果你必须支持iOS< 4您应该使用此模板方法创建一个plist,以便为用户区域设置创建正确的日期格式。

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

给出所以。,2011年2月27日对于我的语言环境。

2011年2月27日星期日用于en_US语言环境

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