开发者

How to format NSDate?

开发者 https://www.devze.com 2023-02-13 22:06 出处:网络
How can I get my NSDate to display in 开发者_开发问答the format for example i.e \"Tue Feb 26, 2011\"Do it right. Don\'t hardcode your date formats. There are countries that are not your country and th

How can I get my NSDate to display in 开发者_开发问答the format for example i.e "Tue Feb 26, 2011"


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


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

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号