NSDate及time()获取的都是设备时间(可通过设置->通用->日期与时间
修改获取的时间值),如果应用想要获取较为准确的时间需要获取网络时间。
代码:
+ (NSDate *)getInternetDate {
NSString *urlString = @"https://www.baidu.com";
urlString = [urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
[request setURL:[NSURL URLWithString: urlString]];
[request setCachePolicy:NSURLRequestReloadIgnoringCacheData];
[request setTimeoutInterval: 2];
[request setHTTPShouldHandleCookies:FALSE];
[request setHTTPMethod:@"GET"];
NSHTTPURLResponse *response;
[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:nil];
//NSLog(@">>>>> response :%@",response);
NSString *date = [[response allHeaderFields] objectForKey:@"Date"];
//NSLog(@">>>>> date :%@",date);
date = [date substringFromIndex:5];
date = [date substringToIndex:[date length]-4];
//NSLog(@">>>>> date :%@",date);
NSDateFormatter *dMatter = [[NSDateFormatter alloc] init];
dMatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
// dMatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"zh-CHS"];
[dMatter setDateFormat:@"dd MMM yyyy HH:mm:ss"];
NSDate *netDate = [[dMatter dateFromString:date] dateByAddingTimeInterval:60*60*8];
return netDate;
}
网友评论