Inconsistent behaviour with NSDateFormatter on two

2020-05-26 12:18发布

I'm having a bit of a problem with NSDateFormatter failing on one user's device (returning nil when parsing a string) and working perfectly when I run it locally (either in the simulator or on my device).

I'm trying to rule out what could be causing a difference in this behaviour. My first thought was the locale but I've tried setting it explicitly to ensure the same locale is always used but it makes no difference.

Here is the code:

NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
[dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZ"];

NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];
[dateFormatter setLocale:locale];
[locale release];

NSDate *theDate = [dateFormatter dateFromString:dateString];
NSLog(@"PARSING DATE %@ AS %@", dateString, theDate);

On the failing device, I get:

PARSING DATE 2010-11-28T20:30:49-0000 AS (null)

But locally I get:

PARSING DATE 2010-11-28T20:30:49-0000 AS 2010-11-28 20:30:49 +0000

This is driving me crazy, am I missing something else?

I am running 4.2 locally (simulator) and on my device (an iPhone 4). The failing device is a 3GS running 4.2.1.

Any ideas would be much appreciated!

1条回答
聊天终结者
2楼-- · 2020-05-26 12:30

I'm pleased to say that I eventually got to the bottom of this issue and I must pass on my thanks to @bendodson on Twitter for helping me out with this. aBitObvious also hit on the issue in his comment above; I'd have up-voted him if I could.

There was one difference between the user's device and mine, and that was that his device was set to use the 12 hour clock and mine was not. This single thing meant that the NSDateFormatter was unable to parse the time in the above examples and returned nil.

By far the biggest issue for me with this problem was being unable to reproduce the problem locally!

So, to be clear, to solve this issue; that is, if you are parsing date/time strings that are in a known, fixed format (often coming from some API as this was in my case), you should set the correct locale for the date formatter, which will often be en_US_POSIX.

...
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[dateFormatter setLocale:locale];
[locale release];

For more information on this, read Apple QA1480.

查看更多
登录 后发表回答