将字符串转换为从 Google 返回的 NSDate 总是 Returns Nil

Converting String To NSDate Returned From Google Always Returns Nil

始终将字符串转换为日期 returns 无。这里一定是遗漏了什么:

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];
[NSDateFormatter dateFormatFromTemplate:@"E MMM d yyyy" options:0 locale:locale];
NSDate *currentDateFromWeb = [dateFormat dateFromString:dateString];

字符串正确打印为:Wed, 28 Jul 2021 13:51:16 GMT

尝试了多种日期格式样式,仍然nil

您可以使用“zzz”作为时区:

"E, d MMM yyyy HH:mm:ss zzz"

所以,这应该给你一个有效的日期:

NSString *str = @"Wed, 28 Jul 2021 13:51:16 GMT";

NSDateFormatter *df = [NSDateFormatter new];
[df setDateFormat:@"E, d MMM yyyy HH:mm:ss zzz"];

NSLocale *locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"];
[df setLocale:locale];

NSDate *d = [df dateFromString:str];

NSLog(@"d: %@", d);

输出(我所在的美国东海岸):

d: Wed Jul 28 09:51:16 2021