當我們需要獲取網(wǎng)絡時間的時候,我們可以從服務器是獲取,但是對于沒有自己服務器的小伙伴來說,只能從網(wǎng)絡上獲取了,這里我們是從百度來獲取網(wǎng)絡時間,具體代碼如下:
- (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;
}
這樣獲取的就是網(wǎng)絡的北京時間