移动开发中,经常会遇到手机本地时间不准确的问题,所以我们有时为了校准时间,还要从服务端端获取。实际上是很简单的,我们每次的HTTP请求头里都可以拿到服务器的时间。
直接看代码 (Objective-C例子):
NSURL *url = [NSURL URLWithString:@"http://mobile.umeng.com"];
NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
[request setHTTPMethod:@"TRACE"];
NSHTTPURLResponse *response = nil;
NSError *error = nil;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
if (error != nil) {
NSLog(@"error = %@", error);
return;
}
NSDictionary *httpHeader = [response allHeaderFields];
NSString *serverDateStr = [httpHeader objectForKey:@"Date"];
NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
dateFormatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
dateFormatter.dateFormat = @"EEE',' dd MMM yyyy HH':'mm':'ss 'GMT'";
NSDate *serverDate = [dateFormatter dateFromString:serverDateStr];
NSLog(@"服务器时间 = %@", serverDate);
你必须 登录后 才能对文章进行评论!