Localized weekday from NSDate in iOs app

2.7k Views Asked by At

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?

2

There are 2 best solutions below

0
On

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;
}
2
On
[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'