当我们需要获取网络时间的时候,我们可以从服务器是获取,但是对于没有自己服务器的小伙伴来说,只能从网络上获取了,这里我们是从百度来获取网络时间,具体代码如下:
- (NSDate *)getInternetDate
{
NSString *urlString = @"http://m.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];
NSString *date = [[response allHeaderFields] objectForKey:@"Date"];
date = [date substringFromIndex:5];
date = [date substringToIndex:[date length]-4];
NSDateFormatter *dMatter = [[NSDateFormatter alloc] init];
dMatter.locale = [[NSLocale alloc] initWithLocaleIdentifier:@"en_US"];
[dMatter setDateFormat:@"dd MMM yyyy HH:mm:ss"];
NSDate *netDate = [[dMatter dateFromString:date] dateByAddingTimeInterval:60*60*8];
NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate: netDate];
NSDate *localeDate = [netDate dateByAddingTimeInterval: interval];
return localeDate;
}
这样获取的就是网络的北京时间