簡體   English   中英

將字符串轉換為從 Google 返回的 NSDate 總是返回 Nil

[英]Converting String To NSDate Returned From Google Always Returns Nil

將字符串轉換為日期總是返回 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

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM