獲取網(wǎng)絡(luò)時(shí)間:
dispatch_async(dispatch_get_global_queue(0, 0), ^{
// 處理耗時(shí)操作的代碼塊...
NSString * nowDate = [self getInternetDate];
if(nowDate ==nil){
NSLog(@">>>>> nowDate nil");
} else {
NSLog(@">>>>> nowDate not nil");
}
NSLog(@">>>>> nowDate :%@",nowDate);
//通知主線程刷新
dispatch_async(dispatch_get_main_queue(), ^{
//回調(diào)或者說(shuō)是通知主線程刷新妻柒,
});
});
- (NSString *)getInternetDate
{
//NSString *urlString = @"https://www.baidu.com";
NSString *urlString = @"http://www.beijing-time.org/time.asp";
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];
NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate: netDate];
NSDate *localeDate = [netDate dateByAddingTimeInterval: interval];
//NSLog(@">>>>> localeDate :%@",localeDate);
NSString *tmpDate = [NSString stringWithFormat:@"%@",localeDate];
tmpDate = [tmpDate stringByReplacingOccurrencesOfString:@" +0000" withString:@""];
//NSLog(@">>>>> localeDate :%@",tmpDate);
NSDateFormatter *format1=[[NSDateFormatter alloc]init];
[format1 setDateFormat:@"yyyy/MM/dd HH:mm:ss"];
NSDate *nowDate = [format1 dateFromString:tmpDate];
NSString *nowDate_ = [format1 stringFromDate:nowDate];
return nowDate_;
}