Reputation: 758
I've got a strange problem regarding NSDate parsing. I have a specific format of date coming from server and that's how I configure my NSDateFormatter:
self.serverDateFormatter = [[NSDateFormatter alloc] init]; [self.serverDateFormatter setDateFormat:@"dd-MM-yyyy HH:mm:ss.SSS"]; [self.serverDateFormatter setTimeZone:[NSTimeZone timeZoneWithName:@"UTC"]];
Using it:
[self.serverDateFormatter dateFromString:[fields valueForKey:@"dateCreated"]];
All worked perfectly fine until build was launched on some device with some locale. My 07-05-2013 10:08:30.000
string coming from server doesn't get parsed and dateFromString
returns nil
.
I don't set a locale for formatter but I hoped dateFormat
is enough to parse the date even without explicit locale.
Any ideas on that? Thanks!
Upvotes: 0
Views: 135
Reputation: 924
The problem is that NSDateFormatter
automatically takes device preferences such as time zones, locale, time format(12 or 24hr). In such a case, your date formatter's format will not match the incoming date from server and so date becomes nil.
Setting locale explicitly will work. Set the folowing locale for 24hr format. For 12hr you set en_US.
NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_GB"];
[dateFormatter setLocale:locale];
Best way is to make sure that you store only 24hr format in your server, if that is possible. Either make sure that you send 24hr format time to server or do a date format conversion in the server, if it is possible.
Upvotes: 0