NSDateFormatter和日本历法

3

当用户没有将公历作为其iPhone默认日历时,我在使用NSDateFormatter时遇到了问题。

NSString *testString = @"2011-01-14";
NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init];
[dateFormat setDateFormat:@"yyyy-MM-dd"];
NSDate *eventDate = [dateFormat dateFromString:testString];
[dateFormat setDateFormat:@"yyyy-MM-dd(EEE)"];
NSString *dateAndLocString = [dateFormat stringFromDate:eventDate];
[dateFormat release];

在使用公历的设备上,dateAndLocString将等于2011-01-13(星期四)。但是当用户使用日本日历时,dateAndLocString将等于2011-01-13(星期三),这是错误的。有没有人知道我可能做错了什么?
1个回答

4
我发现了一个使它正常工作的方法,如果有更好的建议,请告诉我。我们必须使用以下代码在NSDateFormatter上设置首选用户本地化。
[dateFormat setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:[[NSLocale preferredLanguages] objectAtIndex:0]] autorelease]];

这将为NSDateFormatter提供正确的用户区域设置。有些人可能会倾向于使用。

[dateFormat setLocale:[NSLocale currentLocale]];

但是如果用户语言设置为日语,那么在具有日本日历的系统上,[NSLocale currentLocale]会返回en_US@calendar=japanese,这种方法将无法生效。

我不知道为什么NSDateFormatter不能自动处理非公历日历。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接