4

My application is in 2 language one is English and other is Spanish. Now I receive timestamp from the server and I need to show date in "MMM dd, yyyy" formate. this is giving me "Dec 23, 2017" but when I convert it into Spanish then I need to show month name in Spanish. Can you please suggest do I specify 12 month name in Spanish as a short form or NSDateFormatter has this type of option.

  NSDate *date = [dateFormatter dateFromString:[[[webserviceDict valueForKey:@"CurrentWeekEarning"]objectAtIndex:i-1]valueForKey:@"date"]];
                        [dateFormatter setDateFormat:@"MMM dd, yyyy"];
                        strTitle = [NSString stringWithFormat:@"%@",[dateFormatter stringFromDate:date]];
2

3 Answers 3

5

Just set the locale and create a format from template (to set correct ordering):

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.locale = [NSLocale localeWithLocaleIdentifier:@"es"];
[formatter setLocalizedDateFormatFromTemplate:@"yyyyMMMdd"];
NSString *localizedDate = [formatter stringFromDate:[NSDate date]];
NSLog(@"Localized date: %@", localizedDate); // 26 dic 2017

No need to add commas or other separators manually. They are also dependent on language.

The same can be achieved using predefined formats:

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.locale = [NSLocale localeWithLocaleIdentifier:@"es"];
formatter.timeStyle = NSDateFormatterNoStyle;
formatter.dateStyle = NSDateFormatterMediumStyle;
0
3

Swift 5.2 example, setting Spanish "es_ES" locale:

let today = Date()
let formatter = DateFormatter()

formatter.dateStyle = .long

formatter.locale = .init(identifier: "es_ES")
self.dateString = formatter.string(from: today)
0

for specific language you need set locate

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

[formatter setDateStyle:style];

[formatter setDateFormat:@"MMM dd, yyyy"];

NSDate *temp= [formatter dateFromString:strDate];

[formatter setDateFormat:format];

[formatter setLocale:[NSLocale currentLocale]];

1
  • 2
    no need to set style if you are setting the format. manually. Ideally, don't set a specific format but use template to create a format for the locale, otherwise the date won't be localized correctly.
    – Sulthan
    Commented Dec 26, 2017 at 15:12

Not the answer you're looking for? Browse other questions tagged or ask your own question.