Nsdateformatter for specific language like Spanish

99封情书 提交于 2020-04-17 22:51:47

问题


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

回答1:


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;



回答2:


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




回答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)


来源:https://stackoverflow.com/questions/47980254/nsdateformatter-for-specific-language-like-spanish

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!