How to properly convert the Last-Modified header from an HTTP response to an NSDate on iOS

若如初见. 提交于 2019-12-09 04:38:48

问题


I am looking for a fully working solution, one that works with:

  • any iOS locale or timezone
  • any/most HTTP servers
  • Xcode 4.0.2 (see why)

Current broken code:

 NSString lastModifiedString = @"Mon, 06 Jun 2011 12:47:05 GMT";
 NSDateFormatter *df = [[NSDateFormatter alloc] init];  
 //df.dateFormat = @"EEE',' dd MMM yyyy HH':'mm':'ss 'GMT'";
 df.dateFormat = @"EEE, dd MMM yyyy HH:mm:ss z";
 df.locale = [[[NSLocale alloc] initWithLocaleIdentifier:@"en_US_POSIX"] autorelease];  
 df.timeZone = [NSTimeZone timeZoneWithAbbreviation:@"GMT"];  
 NSDate date = [df dateFromString:lastModifiedString];  

I assumed that Last-Modified is supposed to use the same format like other date fields in HTTP spec, meaning to use RFC-1123 / RFC-822

Resources:

  • http://www.w3.org/Protocols/rfc2616/rfc2616-sec14.html HTTP 1.1
  • http://developer.apple.com/library/ios/#qa/qa1480/_index.html

回答1:


The only thing wrong is that you're missing asterisks in-between NSString and lastModifiedString, and also between NSDate and date. Once you put those in, this code works for me.



来源:https://stackoverflow.com/questions/6253044/how-to-properly-convert-the-last-modified-header-from-an-http-response-to-an-nsd

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!