iOS开发之获取百度标准时间

通过NSURL获取百度时间
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
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值