Proud Member
Proud Member

Reputation: 40496

How to get the localized day of an NSDate as string?

I have an NSDate object and must create a label that indicates the day of the week in a short 3-char style like 'Mon', 'Tue', 'Wed', ... and localized to the short representation in any language.

The date formatter EEE has 3 chars but how does that translate to languages like Chinese which probably only have one character?

Upvotes: 2

Views: 6291

Answers (3)

Jawwad
Jawwad

Reputation: 1336

To use the correct locale you'll want to set the dateFormat on the instance of NSDateFormatter using the + dateFormatFromTemplate:options:locale: method.

NSDate *date = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:@"EEE" options:0 locale:[NSLocale currentLocale]];
NSLog(@"Weekday using %@: %@", [[NSLocale currentLocale] localeIdentifier], [dateFormatter stringFromDate:date]);

// Test what Chinese will look like without changing device locale in settings
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"];
NSLog(@"Weekday using zh_CN: %@", [dateFormatter stringFromDate:date]);

This prints:

Weekday using en_US: Thu
Weekday using zh_CN: 周四

Upvotes: 4

Nekto
Nekto

Reputation: 17877

This will print what you need:

NSDate *date = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"EEEE"];
NSString *day = [formatter stringFromDate:date];
[formatter release];
if ([day length] > 3) day = [day substringToIndex:3];
NSLog(@"%@", day);

Upvotes: 1

Nitish
Nitish

Reputation: 14113

NSDate *date = [NSDate date];
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"EEE"];
NSString *strDate = [formatter stringFromDate:date];
[formatter release];
//Commented out the following line as weekday can be of one letter (requirement changed)
//strDate = [strDate substringToIndex:3];   //This way Monday = Mon, Tuesday = Tue

Upvotes: 8

Related Questions