同一個日期,在不同語言環境下該長什麼樣子?英文環境是 January 27, 2014,中文環境是 2014 年 1 月 27 日。這是多語言 App 必須面對的基本問題,而答案往往不是自己拼字串。
Apple 已經在 NSDateFormatter 裡處理好各語言的排列習慣與月份名稱,直接用固定樣式即可:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init]; [dateFormatter setTimeStyle:NSDateFormatterNoStyle]; [dateFormatter setDateStyle:NSDateFormatterFullStyle]; NSDate *date = [NSDate date]; NSLog(@"default: %@", [dateFormatter stringFromDate:date]); NSLocale *zhLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh_CN"]; [dateFormatter setLocale:zhLocale]; NSLog(@"zh_CN: %@", [dateFormatter stringFromDate:date]); NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]; [dateFormatter setLocale:usLocale]; NSLog(@"en_US: %@", [dateFormatter stringFromDate:date]); NSLocale *gbLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"]; [dateFormatter setLocale:gbLocale]; NSLog(@"en_GB: %@", [dateFormatter stringFromDate:date]); NSLocale *frLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"fr_FR"]; [dateFormatter setLocale:frLocale]; NSLog(@"fr_FR: %@", [dateFormatter stringFromDate:date]);
輸出結果很能說明問題:
同樣是 FullStyle,英美兩地的日與月順序就不一樣,法文的星期與月份又是另一套拼法。這些差異若靠 if-else 判斷語言自己組,遲早會漏。
固定樣式只涵蓋完整的年月日。如果需求是「只要年月」,直覺做法是自己設 dateFormat,中文寫 yMMMM、英文寫 MMMMy——但這又回到了逐一語言設定字串的老路。
更好的做法是讓系統依區域產生合適的格式模板:
NSString *dateComponents = @"yMMMMd";
NSString *dateFormat = [NSDateFormatter dateFormatFromTemplate:dateComponents
options:0
locale:usLocale];
把「我要哪些成分」告訴系統,由它依該區域的習慣排出正確順序與分隔符號。實際輸出如下:
需要年月時,把 components 改成 @"yMMMM" 即可,其餘邏輯完全不動。
NSDateFormatter *monthAndYearFormatter = [[NSDateFormatter alloc] init];
monthAndYearFormatter.dateFormat =
[NSDateFormatter dateFormatFromTemplate:@"yMMMM" options:0 locale:[NSLocale currentLocale]];
NSLog(@"%@", [monthAndYearFormatter stringFromDate:[NSDate date]]);
第一,NSDateFormatter 的建立成本不低,請建立一次重複使用,不要放在每回呼叫的方法裡;同時它是非執行緒安全的,多執行緒環境下請每執行緒各持一份或用 GCD 序列化存取。
第二,數字的格式化是另一個問題(千分位、阿拉伯數字與本地數字系統的差異),那要交給 NSNumberFormatter 處理,兩者不要混用。