转换谷歌返回的日期字符串为NSDate始终返回nil如何解决?
字符串转NSDate返回nil问题解决
核心问题点
- 日期格式与实际输入的
Wed, 28 Jul 2021 13:51:16 GMT不匹配,漏了逗号、时间字段、时区标识 - 没有为
NSDateFormatter指定en_US_POSIX类型的locale,当设备系统语言非英文时,无法识别英文的星期、月份缩写 - 调用
dateFormatFromTemplate方法后没有将返回的格式字符串赋值给格式化器的dateFormat属性,相当于没有设置解析规则
修正后的代码
NSHTTPURLResponse *httpResponse = nil; [NSURLConnection sendSynchronousRequest:request returningResponse:&httpResponse error:nil]; NSString *dateString = [[httpResponse allHeaderFields] objectForKey:@"Date"]; DebugLog(@" *** GOOGLE DATE: %@ ****",dateString); NSDateFormatter *dateFormat = [[NSDateFormatter alloc] init]; // 固定使用en_US_POSIX locale,屏蔽系统语言/区域设置对解析的影响 NSLocale *enPOSIXLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"]; dateFormat.locale = enPOSIXLocale; // 设置和输入字符串完全匹配的解析格式 dateFormat.dateFormat = @"EEE, dd MMM yyyy HH:mm:ss z"; NSDate *currentDateFromWeb = [dateFormat dateFromString:dateString];
补充说明
HTTP响应头的Date字段属于标准RFC1123时间格式,必须使用固定的英文locale才能正常解析,格式字符和输入字符串的字符顺序、分隔符必须完全对应,少一个符号都会返回nil。
内容的提问来源于stack exchange,提问作者JSA986
相关产品推荐
相关产品推荐

