Objective-C
- (void)initWithNSURLRequest
{
NSURL *url=[NSURL URLWithString:@"http://www.baidu.com"];
NSURLRequest *request=[NSURLRequest requestWithURL:url];
NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];
[connection start];
}
// request的回调方法
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
NSLog(@"response%@",response);
NSHTTPURLResponse *httpResponse=(NSHTTPURLResponse *)response;
if ([response respondsToSelector:@selector(allHeaderFields)]) {
NSDictionary *dic=[httpResponse allHeaderFields];
NSString *time=[dic objectForKey:@"Date"];
// 将 Thu, 29 11 2012 19:35:18 EST 格式转化为 2012-29-11 19:35:18
NSDateFormatter *dateFormatter = [NSDateFormatter new];
dateFormatter.dateFormat = @"EEE, dd MM yyyy HH:mm:ss zzz";
// // 将语言转化成英文的
dateFormatter.locale=[NSLocale localeWithLocaleIdentifier:@"en_US"];
NSDate *date = [dateFormatter dateFromString:time];
dateFormatter.dateFormat = @"yyyy-MM-dd HH:mm:ss";
// 将语言转化成中文的
dateFormatter.locale = [NSLocale localeWithLocaleIdentifier:@"zh_CN"];
NSString *localDateString = [dateFormatter stringFromDate:date];
NSLog(@"localDateString===%@", localDateString);
}
}
Swift
func getBaiduTime(handler:(date:String)->(),syscn:Bool=false)
{
var request : ASIHTTPRequest = ASIHTTPRequest (URL: NSURL(string: "http://www.baidu.com"))
request.timeOutSeconds = 30
request.setCompletionBlock { () -> Void in
// println("请求数据完成==\(request.responseHeaders)")
var json: NSDictionary = request.responseHeaders
var time = json["Date"] as String
handler(date: self.stringWithFormat(time))
}
request.setFailedBlock { () -> Void in
println("asi error:%@",request.error.debugDescription)
}
if syscn{
request.sendRequestSynchronous()
}else{
request.sendRequestAsynchronous()
}
}
func stringWithFormat(timeStr:String)->String
{
var dateFormatter = NSDateFormatter()
dateFormatter.dateFormat = "EEE, dd MM yyyy HH:mm:ss zzz"
// 将语言转化成英文的
dateFormatter.locale = NSLocale(localeIdentifier: "en_US")
var dateTime = dateFormatter.dateFromString(timeStr) as NSDate?
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
// 将语言转化成中文的
dateFormatter.locale = NSLocale(localeIdentifier: "zh_CN")
var dateString:String = dateFormatter.stringFromDate(dateTime!) as String
return dateString
}