iphone - NSDate 完整样式但没有年份

标签 iphone nsdate nsdateformatter

我正在使用 iPhone 的 Objective C,并且有一个 NSDate,我想以完整样式显示但不显示年份。现在我正在使用下面的代码,但它也显示年份,但我不想要这样。因为我想以正确的区域格式显示日期,所以我不能只删除末尾的年份,因为在某些国家/地区,年份不会在末尾,而是在中间或开头。

NSDate *testdate = [NSDate date];
NSDateFormatter *dateFormattertest = [[NSDateFormatter alloc] init];
[dateFormattertest setDateStyle:NSDateFormatterFullStyle];
[dateFormattertest setTimeStyle:NSDateFormatterNoStyle];
NSString *formattedDateString = [dateFormattertest stringFromDate:testdate];
NSLog(formattedDateString);

In US this give me:
Thursday, January 14, 2010

In Sweden this give me:
torsdag, 2010 januari 14

这个问题有什么解决办法吗?还有一个问题,在哪里可以找到有关如何使用 NSDateFormatter 的 setDateFormat 的信息?我找不到有关 API 中不同字母代表什么的信息。

最佳答案

我知道这是一个很老的问题,但这是我在 SO 上发现的唯一一个谈论我遇到的相同问题的问题。

这里使用的关键方法是:dateFormatFromTemplate

您想要设置格式,而不是设置样式:

NSDate *testdate = [NSDate date];

NSLocale *currentLocale = [NSLocale currentLocale];

// Set the date components you want
NSString *dateComponents = @"EEEEMMMMd";

// The components will be reordered according to the locale
NSString *dateFormat = [NSDateFormatter dateFormatFromTemplate:dateComponents options:0 locale:currentLocale];
NSLog(@"Date format for %@: %@", [currentLocale displayNameForKey:NSLocaleIdentifier value:[currentLocale localeIdentifier]], dateFormat);

NSDateFormatter *dateFormatter =[[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:dateFormat];

NSString *formattedDateString = [dateFormatter stringFromDate:testdate];
NSLog(formattedDateString);

特别感谢:http://oleb.net/blog/2011/11/working-with-date-and-time-in-cocoa-part-2/

关于iphone - NSDate 完整样式但没有年份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2064145/

相关文章:

ios - 获取第一个和最后一个工作日。一年中第一周和最后几周的奇怪行为

objective-c - 如果是没有 AM/PM 的 12 小时格式,有什么方法可以识别时间?

swift - dateFromString() 返回不正确的日期

iphone - 如何以有效的方式为 IOS 应用程序创建 Sqlite 数据库?

android - 利用具有Android引擎的旧/新设备来驱动其他电子设备

objective-c - JSON 日期到 NSDate 并返回

swift - 当设备时间为 24 小时格式时应用程序崩溃

iphone - 在启动动画之前修改 iPhone 动画容器 View

iphone - ';' token 错误之前预期的 '('

swift - 如何在 Swift 中减去两个 NSDates?