您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

多語言與區域下的日期顯示處理

編輯:iOS 開發綜合

同一個日期,在不同語言環境下該長什麼樣子?英文環境是 January 27, 2014,中文環境是 2014 年 1 月 27 日。這是多語言 App 必須面對的基本問題,而答案往往不是自己拼字串。

用 NSDateFormatter,不要自己發明輪子

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

輸出結果很能說明問題:

  • en_US:Monday, January 27, 2014
  • zh_CN:2014 年 1 月 27 日 星期一
  • en_GB:Monday, 27 January 2014
  • fr_FR:lundi 27 janvier 2014

同樣是 FullStyle,英美兩地的日與月順序就不一樣,法文的星期與月份又是另一套拼法。這些差異若靠 if-else 判斷語言自己組,遲早會漏。

只顯示年月時怎麼辦

固定樣式只涵蓋完整的年月日。如果需求是「只要年月」,直覺做法是自己設 dateFormat,中文寫 yMMMM、英文寫 MMMMy——但這又回到了逐一語言設定字串的老路。

更好的做法是讓系統依區域產生合適的格式模板:

NSString *dateComponents = @"yMMMMd";
NSString *dateFormat = [NSDateFormatter dateFormatFromTemplate:dateComponents
                                                     options:0
                                                      locale:usLocale];

把「我要哪些成分」告訴系統,由它依該區域的習慣排出正確順序與分隔符號。實際輸出如下:

  • English (United States):MMMM d, y
  • English (United Kingdom):d MMMM y
  • français (France):d MMMM y
  • 中文(中國):y 年 M 月 d 日

需要年月時,把 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 處理,兩者不要混用。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved