问题
This was working fine before compiling with iOS4.0 and I can't figure out what's wrong.
Here's the problem. I send my app scores from my database with a date/time on it. My goal is to store that in CoreData. When I use the code below I get a null value for the date.
Code:
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"US"];
[dateFormatter setLocale:locale];
[dateFormatter setDateFormat:@"MM/dd/yyyy HH:mm:ss ZZZ"];
currentDownloadedScore.dateEntered = [dateFormatter dateFromString:self.currentValue];
NSLog(@"Date CV: %@",self.currentValue);
NSLog(@"Date: %@",[currentDownloadedScore.dateEntered description]);
[locale release];
[dateFormatter release];
Here's the result in the debugger:
2010-07-16 08:15:35.741 MyApp[75003:207] Date CV: 07/16/2010 04:21:00 +00:00
2010-07-16 08:15:35.742 MyApp[75003:207] Date: (null)
2010-07-16 08:15:35.745 MyApp[75003:207] Date CV: 07/16/2010 01:09:26 +00:00
2010-07-16 08:15:35.749 MyApp[75003:207] Date: (null)
Any help is appreciated! Thanks.
回答1:
I found the issue. It seems like the ZZZ
part of the formating NO LONGER accepts the colon :
in the time.
Works: 07/16/2010 04:21:00 +0000
Doesn't work: 07/16/2010 04:21:00 +00:00
To support the current apps that are out, all I did was search for the +00:00
part in the string and replace it with +0000
. TADA! It works!
回答2:
NSDateFormatter has gotten very picky in iOS4. This other SO question had the same problem and has a couple different solutions.
回答3:
I had the same problem. For me, the problem was that I had a line break in my XML feed for the date, so this code fixed it for me:
[currentDate replaceOccurrencesOfString:@"\n" withString:@"" options:NSCaseInsensitiveSearch range:NSMakeRange(0,[currentDate length])];
来源:https://stackoverflow.com/questions/3264729/null-value-from-nsdateformatter-from-xml