1. 程式人生 > >iOS開發---獲取網路時間(百度時間)

iOS開發---獲取網路時間(百度時間)

- (NSDate *)getInternetDate{

    NSString *urlString = @"http://m.baidu.com";

    urlString = [urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];

    // 例項化NSMutableURLRequest,並進行引數配置

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];

    [request setURL:[NSURL URLWithString: urlString]];

    [request setCachePolicy:NSURLRequestReloadIgnoringCacheData];

    [request setTimeoutInterval: 2];

    [request setHTTPShouldHandleCookies:FALSE];

    [request setHTTPMethod:@"GET"];

    NSError *error = nil;

    NSHTTPURLResponse *response;

    [NSURLConnection sendSynchronousRequest:request

                          returningResponse:&response error:&error];

    // 處理返回的資料

    if (error) {

        return [NSDate date];

    }

    NSString *date = [[response allHeaderFields] objectForKey:@"Date"];

    date = [date substringFromIndex:5];//index到這個字串的結尾

    date = [date substringToIndex:[date length]-4];//從索引0到給定的索引index

    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小時

    NSTimeZone *zone = [NSTimeZone systemTimeZone];

    NSInteger interval = [zone secondsFromGMTForDate: netDate];

    netDate = [netDate  dateByAddingTimeInterval: interval];

    return netDate;

}