NSDateFormatter和日历 [英] NSDateFormatter and Japanese calendar
问题描述
当用户没有使用公历作为iPhone的默认日历时,我遇到使用NSDateFormatter的问题。
I'm having issues using NSDateFormatter when the user isn't using the Gregorian calendar as their default calendar for the iPhone.
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(周三),这是错误的。
On a device using the Gregorian calendar dateAndLocString will be equal to 2011-01-13(Thu) But when the user is using the Japanese calendar dateAndLocString will be equal to 2011-01-13(Wed), which is wrong.
任何人都知道什么我可能做错了吗?
Anyone have any idea what I might be doing incorrectly?
推荐答案
我找到了一种方法让它正常工作,如果有人有更好的建议请让我知道。我们必须使用以下代码行在NSDateFormatter上设置首选用户本地。
I found a way to get this to work correctly, if anyone has a better suggestion please let me know. We have to set the preferred user local on the NSDateFormatter using the following line of code.
[dateFormat setLocale:[[[NSLocale alloc] initWithLocaleIdentifier:[[NSLocale preferredLanguages] objectAtIndex:0]] autorelease]];
这将为NSDateFormatter提供正确的用户区域设置。有些人可能会想要使用
This will provide the correct user locale to the NSDateFormatter. Some people might be tempted to use
[dateFormat setLocale:[NSLocale currentLocale]];
但这不能用作 [NSLocale currentLocale]
在具有日语日历的系统上,即使用户语言设置为日语,也会返回en_US @ calendar = japanese。
But this will not work as [NSLocale currentLocale]
on a system with a Japanese calendar returns en_US@calendar=japanese even if the user language is set to Japanese.
我不知道为什么NSDateFormatter不起作用自动在非公历日历上。
I have no clue why NSDateFormatter doesn't work automatically on non Gregorian calendars.
这篇关于NSDateFormatter和日历的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!