Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to format NSDate?

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

like image 290
Christian Gossain Avatar asked Nov 28 '22 02:11

Christian Gossain


1 Answers

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

like image 132
Matthias Bauch Avatar answered Dec 06 '22 00:12

Matthias Bauch