我想显示一个没有一年的日期.例如:“8月2日”(美国)或“02.08”. (德国)
它也适用于一大堆其他地区.
到目前为止我唯一的想法是用一年的正常格式,然后从生成的字符串中删除年份.
解决方法
+ (NSString *)dateFormatFromTemplate:(NSString *)template options:(NSUInteger)opts locale:(NSLocale *)locale
根据文档:
Returns a localized date format string representing the given date format components arranged appropriately for the specified locale.
Return Value
A localized date format string representing the date format components given in template,arranged appropriately for the locale specified by locale.The returned string may not contain exactly those components given in template,but may—for example—have locale-specific adjustments applied.
Discussion
Different locales have different conventions for the ordering of date components. You use this method to get an appropriate format string for a given set of components for a specified locale (typically you use the current locale—see currentLocale).
The following example shows the difference between the date formats for British and American English:
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]]);
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。