Search code examples
iosobjective-cnsdate

Converting String To NSDate Returned From Google Always Returns Nil


Converting string to date always returns nil. Must be missing something here:

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];

String prints correctly as: Wed, 28 Jul 2021 13:51:16 GMT

Tried a variety of date formatter styles, still nil


Solution

  • You can use "zzz" for the time-zone:

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

    So, this should give you a valid date:

    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);
    

    Output (where I am, US East Coast):

    d: Wed Jul 28 09:51:16 2021