NSDateFormatter and Japanese calendar

2019-02-18 23:35发布

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];

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?

1条回答
爷的心禁止访问
2楼-- · 2019-02-19 00:23

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]];

This will provide the correct user locale to the NSDateFormatter. Some people might be tempted to use

[dateFormat setLocale:[NSLocale currentLocale]];

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.

I have no clue why NSDateFormatter doesn't work automatically on non Gregorian calendars.

查看更多
登录 后发表回答