Chandni
Chandni

Reputation: 690

Nsdateformatter for specific language like Spanish

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]];

Upvotes: 4

Views: 2446

Answers (3)

iGhost
iGhost

Reputation: 1054

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)

Upvotes: 3

Sulthan
Sulthan

Reputation: 130200

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;

Upvotes: 5

hfetoui
hfetoui

Reputation: 11

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]];

Upvotes: 0

Related Questions