NSDateFormatter:date根据currentLocale,无年份

这不能太困难..

我想显示一个没有年份的date。 例如:“8月2日”(美国)或“02.08”。 (德国)它也必须适用于其他一些地区。

我到目前为止唯一的想法是做一个正常的格式与年,然后从生成的string中删除年份。

我想你需要看看:

+ (NSString *)dateFormatFromTemplate:(NSString *)template options:(NSUInteger)opts locale:(NSLocale *)locale 

根据文档:

返回一个本地date格式string,表示给定的date格式组件适合指定的区域设置。 返回值本地date格式string,表示模板中给出的date格式组件,适合locale指定的区域设置。

返回的string可能并不完全包含模板中给出的那些组件,但可能(例如)应用了特定于区域的调整。

讨论

不同的语言环境对date组件的sorting有不同的约定。 您可以使用此方法为给定的语言环境的一组给定组件获取适当的格式string(通常使用当前的语言环境 – 请参阅currentLocale)。

以下示例显示了英式和美式英语的date格式之间的差异:

 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 

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

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

看到这里: NSDateFormatter类参考

你给出的两个例子是非常不同的。 一个使用缩写的月份名称,而另一个使用两位数的月份数字。 一个使用一天的序数(“第二”),而另一个使用两位数的天数。

如果你可以接受使用相同的一般格式的所有语言环境,然后使用NSDateFormatter dateFormatFromTemplate:options:locale:

 NSString *localFormat = [NSDateFormatter dateFormatFromTemplate:@"MMM dd" options:0 locale:[NSLocale currentLocale]]; 

这个调用的结果将返回一个格式string,你可以使用NSDateFormatter setDateFormat: 月份和date的顺序适用于语言环境以及任何应添加的附加标点符号。

但是,再次,这不会解决您的确切需求,因为您看起来想要为每个区域设置完全不同的格式。

Swift 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 

template来匹配您的需求。

Doc和示例,以帮助您确定所需的模板。