NSDateFormatter:根据currentLocale的日期,没有Year

scr*_*rrr 15 objective-c nsdateformatter ios

这不可能太难..

我想显示没有年份的日期.例如:"Aug,2nd"(美国)或"02.08".(德国)它必须适用于许多其他语言环境.

到目前为止,我唯一的想法是使用年份进行正常格式,然后从生成的字符串中删除年份部分.

Jor*_*ide 22

我想你需要看看:

+ (NSString *)dateFormatFromTemplate:(NSString *)template options:(NSUInteger)opts locale:(NSLocale *)locale
Run Code Online (Sandbox Code Playgroud)

根据文档:

返回一个本地化的日期格式字符串,表示为指定的语言环境适当排列的给定日期格式组件.返回值一个本地化的日期格式字符串,表示模板中给出的日期格式组件,适合于由locale指定的语言环境.

返回的字符串可能不完全包含模板中给出的那些组件,但可能 - 例如 - 应用了特定于语言环境的调整.

讨论

不同的语言环境对日期组件的排序有不同的约定.您可以使用此方法为指定区域设置的给定组件集获取适当的格式字符串(通常使用当前区域设置 - 请参阅currentLocale).

以下示例显示英国和美国英语的日期格式之间的差异:

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

NSString *dateFormat;
// NOTE!!! I removed the 'y' from the example
NSString *dateComponents = @"MMMMd";  //@"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
Run Code Online (Sandbox Code Playgroud)

额外代码(将其添加到上面的代码中):

// 
NSDateFormatter * formatter = [[NSDateFormatter alloc] init];
formatter.locale = gbLocale;
formatter.dateFormat = dateFormat;
NSLog(@"date: %@", [formatter stringFromDate: [NSDate date]]);
Run Code Online (Sandbox Code Playgroud)

请参见此处: NSDateFormatter类参考

  • @scrrr我很困惑.这就是我给你的答案. (3认同)

rma*_*ddy 19

你给出的两个例子彼此非常不同.一个使用缩写的月份名称,而另一个使用2位数的月份号码.一个使用日序("2nd"),而另一个使用2位数日.

如果您可以接受对所有语言环境使用相同的通用格式,那么请使用NSDateFormatter dateFormatFromTemplate:options:locale:.

NSString *localFormat = [NSDateFormatter dateFormatFromTemplate:@"MMM dd" options:0 locale:[NSLocale currentLocale]];
Run Code Online (Sandbox Code Playgroud)

此调用的结果将返回您可以使用的格式字符串NSDateFormatter setDateFormat:.月份和日期的顺序适用于区域设置以及应添加的任何其他标点符号.

但同样,这并不能解决您的确切需求,因为您希望每种语言环境都有完全不同的格式.


fro*_*ouo 6

迅捷3

let template = "EEEEdMMM"
let locale = NSLocale.current // the device current locale

let format = DateFormatter.dateFormat(fromTemplate: template, options: 0, locale: locale)
let formatter = DateFormatter()
formatter.dateFormat = format

let now = Date()
let whatYouWant = formatter.string(from: now) // Sunday, Mar 5
Run Code Online (Sandbox Code Playgroud)

template根据您的需要玩。

此处的文档和示例可帮助您确定所需的模板。