Reputation: 6433
I'm trying to get the localized weekday from an nsdate object
+ (NSString *)localizedWeekdayForDate:(NSDate *)date
{
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSString *language = [[[NSBundle mainBundle] preferredLocalizations] objectAtIndex:0];
dateFormatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:@"EEEE" options:0 locale:[NSLocale localeWithLocaleIdentifier:language]];
NSString *formattedDateString = [dateFormatter stringFromDate:date];
return formattedDateString;
}
The language string is always "en" ... even thou the device language is not english... I tried [NSLocale currentLocale]; as well as preferedLanguages... this also doesn't work..
Any suggestions?
Upvotes: 4
Views: 2776
Reputation: 112857
[NSDateFormatter dateFormatFromTemplate:@"EEEE" options:0 locale:[NSLocale localeWithLocaleIdentifier:language]]
Does not set the locale, it only returns a NSString
. The locale needs to be set with:
- (void)setLocale:(NSLocale *)locale
Examples:
ObjectiveC
NSDate *date = [NSDate date];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *locale = [NSLocale localeWithLocaleIdentifier:@"fr"];
[dateFormatter setLocale:locale];
[dateFormatter setDateFormat:@"EEEE"];
NSString *formattedDateString = [dateFormatter stringFromDate:date];
NSLog(@"formattedDateString: '%@'", formattedDateString);
NSLog output:
formattedDateString: 'mardi'
Swift 3
let date = Date()
let dateFormatter = DateFormatter()
let locale = Locale(identifier:"fr")
dateFormatter.locale = locale
dateFormatter.dateFormat = "EEEE"
let formattedDateString = dateFormatter.string(from:date)
print("formattedDateString: \(formattedDateString)")
Output:
formattedDateString: 'mardi'
Upvotes: 6
Reputation: 69469
You are forgetting to set the local of the dateFormatter:
+ (NSString *)localizedWeekdayForDate:(NSDate *)date
{
NSLocale *currentLocale = [NSLocale currentLocale];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.locale = currentLocale;
dateFormatter.dateFormat = [NSDateFormatter dateFormatFromTemplate:@"EEEE" options:0 locale:currentLocale];
NSString *formattedDateString = [dateFormatter stringFromDate:date];
return formattedDateString;
}
Upvotes: 0