Looks like locale
setter has some magic, which forces the dateFormatter
works properly
+(NSDate*)dateTimeFromJSONDateString:(NSString*)dateString{ //dateString i.e. 2013-11-19T12:47:38+04:00
static NSDateFormatter *kDateFormatter;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
kDateFormatter = [[NSDateFormatter alloc] init];
// kDateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"ru_RU"];
[kDateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZ"];
});
NSLog(@"%@", kDateFormatter.locale.localeIdentifier); // this one prints 'ru_RU' always either I set kDateFormatter.locale explicitly or not
return [kDateFormatter dateFromString:dateString];
}
so this method returns nil
when 6th line is commented, otherwise it returns correct date. Am I doing something wrong, or we have sdk bug here?
The problem solved by setting the formatter's locale to en_US_POSIX
. It is necessary while parsing fixed-format date strings because the format of the date strings is constant unlike device' locale.
The code should be like
+(NSDate*)dateTimeFromJSONDateString:(NSString*)dateString{
static NSDateFormatter *_dateFormatter;
static dispatch_once_t onceToken;
dispatch_once(&onceToken, ^{
_dateFormatter = [[NSDateFormatter alloc] init];
_dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[_dateFormatter setDateFormat:@"yyyy-MM-dd'T'HH:mm:ssZZZZ"];
});
if (string)
return [_dateFormatter dateFromString:string];
else
return nil;
}
I don't know if it's documented or is a bug, but in iOS 7 (or XCode 5, not sure of the origin of the problem) you have to set the explicitly locale of NSDateFormatter before parsing date strings, or you get nil dates
Until XCode 5/iOS 7, NSDateFormatter had as default the locale of the phone, and you didn't get a nil date
I found this problem mantaining old applications, that suddenly started returning nil dates
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.