項目需求,要求獲取用戶進入某一個界面的時間和退出界面的時間,當時用的系統時間,但是有些用戶手機時間會時間不準確,這就導致傳到後臺的時間不準確,所以現在需要獲取網絡時間,相對準確。
網絡上搜索了一下,可以說都是那一個模版的變形。天下文章一大抄,充分體現出來了。我也是抄的,但是改了一部分,不能說是原創吧,但是也不算轉載吧,所以就請大家多吐槽,這樣我才能成長。
好了廢話不多說,上代碼
+ (void)getInternetDateNowWithType:(NSInteger)type withPagyId:(NSInteger)pageId{
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:5];
[request setHTTPShouldHandleCookies:FALSE];
[request setHTTPMethod:@"GET"];
// NSError *error = nil;
// NSHTTPURLResponse *response;
// [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];
//demo上面爲同步請求,這裏我們用不到 會出現界面卡頓現象,所以用下面的異步請求替換
__block NSDate *localeDate;
[NSURLConnection sendAsynchronousRequest:request queue:[[NSOperationQueue alloc] init] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable
connectionError) {
//要把網絡數據強轉 不然用不了下面那個方法獲取不到內容(個人感覺,不知道對不)
NSHTTPURLResponse *responsee = (NSHTTPURLResponse *)response;
NSString *date = [[responsee 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]; //這個獲取時間是正常時間,但是轉化後會快8個小時,所以取的沒有處理8小時的時間
NSDate *netDate = [dMatter dateFromString:date];
NSTimeZone *zone = [NSTimeZone systemTimeZone];
NSInteger interval = [zone secondsFromGMTForDate: netDate];
localeDate = [netDate dateByAddingTimeInterval: interval];
NSLog(@"%@________1",localeDate);
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:@"YYYY-MM-dd HH:mm:ss"];
NSString *nowtimeStr = [NSString string];
nowtimeStr = [formatter stringFromDate:localeDate];
}];
}
由於是部分代碼,請大家做個參考,有錯誤的地方還請大家指正。