【问题标题】:Converting String To NSDate Returned From Google Always Returns Nil将字符串转换为从 Google 返回的 NSDate 始终返回 Nil
【发布时间】:2021-10-04 07:47:02
【问题描述】:

将字符串转换为日期总是返回 nil。这里一定漏掉了什么:

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

【问题讨论】:

    标签: ios objective-c nsdate


    【解决方案1】:

    您可以使用“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
    

    【讨论】:

    • 太棒了,谢谢!这个时区尝试了很多组合!再次感谢
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-09
    • 1970-01-01
    • 1970-01-01
    • 2019-07-13
    • 2015-02-25
    • 2016-02-23
    相关资源
    最近更新 更多