簡體   English   中英

如何確定區域設置的日期格式是月/日還是日/月?

[英]How to determine if locale's date format is Month/Day or Day/Month?

在我的iPhone應用程序中,我希望能夠確定用戶的區域設置的日期格式是月/日(即1月5日的1/5)還是日/月(即1月5日的5/1)。 我有一個自定義NSDateFormatter ,它不使用NSDateFormatterShortStyle (11/23/37)等基本格式之一。

在理想的世界中,我想使用NSDateFormatterShortStyle,但只是不顯示年份(只有月份和日期#)。 實現這一目標的最佳方法是什么?

您想使用NSDateFormatter的+ dateFormatFromTemplate:options:locale:

這是一些Apple示例代碼:

NSLocale *usLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
NSLocale *gbLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];

NSString *dateFormat;
NSString *dateComponents = @"yMMMMd";

dateFormat = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:usLocale];
NSLog(@"Date format for %@: %@",
    [usLocale displayNameForKey:NSLocaleIdentifier value:[usLocale localeIdentifier]], dateFormat);

dateFormat = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:gbLocale];
NSLog(@"Date format for %@: %@",
    [gbLocale displayNameForKey:NSLocaleIdentifier value:[gbLocale localeIdentifier]], dateFormat);

// Output:
// Date format for English (United States): MMMM d, y
// Date format for English (United Kingdom): d MMMM y

在示例代碼的基礎上,這是一個單行程序,用於確定當前區域設置是否為第一天(nb。我刪除了'y',因為這與我們的問題無關):

BOOL dayFirst = [[NSDateFormatter dateFormatFromTemplate:@"MMMMd" options:0 locale:[NSLocale currentLocale]] hasPrefix:@"d"];

NB。 dateFormatFromTemplate的文檔聲明“返回的字符串可能不包含模板中給出的那些組件,但可能 - 例如 - 應用了特定於語言環境的調整。” 鑒於此,有時測試可能由於未知格式而返回FALSE(意味着它在默認情況下默認為月份優先)。 確定您喜歡哪個默認值,或者您是否需要增強測試以支持其他語言環境。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM