iOS擷取網路時間與轉換格式

來源:互聯網
上載者:User

標籤:

 

[NSDate date]可以擷取系統時間,但是會造成一個問題,使用者可以自己修改手機系統時間,所以有時候需要用網路時間而不用系統時間。擷取網路標準時間的方法:

1、先在需要的地方實現下面的代碼,建立一個URL並且串連

1 NSURL *url=[NSURL URLWithString:@"http://www.baidu.com"];2     NSURLRequest *request=[NSURLRequest requestWithURL:url];3     NSURLConnection *connection=[[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];4     [connection start];

2、實現代理方法,接收回應的資料(需要聲明<NSURLConnectionDataDelegate>)

/** *  代理方法 */- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{//      NSLog(@"response--%@",response);        NSHTTPURLResponse *httpResponse=(NSHTTPURLResponse *)response;    if ([response respondsToSelector:@selector(allHeaderFields)]) {        NSDictionary *dict=[httpResponse allHeaderFields];//      NSLog(@"dict--%@",dict);        NSString *time=[dict objectForKey:@"Date"];        NSLog(@"date--%@___class---%@",date,[date class]);    }}

 這時候接收到的資料是這樣的

Tue, 30 Jun 2015 03:55:54 GMT

類型是NSCFString,如果我們需要用的是NSDate的資料就需要進行轉換。。。。。。

轉換的方法是。。。。。。。。。。。你需要瞭解的知識是截取字串,格式化......具體做法是這樣的,可以寫一個轉換的函數,把字串作為參數傳進來,1、截取字串

NSString *timeStr=[str substringWithRange:NSMakeRange(5, 20)];//截取字串

2、格式化

NSDateFormatter *formatter = [[NSDateFormatter alloc] init];

[formatter setDateFormat:@"dd MMM yyyy HH:mm:ss"];//設定源時間字串的格式

NSDate* date = [formatter dateFromString:timeStr];//將源時間字串轉化為NSDate

在模擬器上啟動並執行時候,你會發現出來的資料比標準時間還少了8小時。。。。。。Why????

少了這個

NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"GMT"];

[formatter setTimeZone:timeZone];

好,以為做完了,模擬器上也正常了,真機試試,出來的值為null.....好煩...其實還少了配置地區

是這樣:

NSLocale *local=[[NSLocale alloc]initWithLocaleIdentifier:@"en_US_POSIX"];

[formatter setLocale:local];//需要配置地區,不然會造成模擬器正常,真機日期為null的情況

en_US_POSIX是什嗎?查了一下,還有另外一個選擇,是en_US,兩個有什麼區別呢?目前換了另一個參數看上去結果是一樣的,但是蘋果推薦用en_US_POSIX,文檔上說的意思大約是,en_US_POSIX和en_US出來的時間是一樣的,但是如果美國,在未來的某個時刻,它改變日期格式的方式,用“en_US”將改變以反映新的行為,但“en_US_POSIX”不會,在機器上(“en_US_POSIX”適用於iPhone作業系統一樣,它在Mac OS X上。

最後付上轉碼:

-(NSDate *)dateFromNSString:(NSString *)str{    //Tue, 30 Jun 2015 03:55:54 GMT    //30 Jun 2015 03:55:54     NSString *timeStr=[str substringWithRange:NSMakeRange(5, 20)];//截取字串     NSDateFormatter *formatter = [[NSDateFormatter alloc] init];     NSTimeZone *timeZone = [NSTimeZone timeZoneWithName:@"GMT"];     NSLocale *local=[[NSLocale alloc]initWithLocaleIdentifier:@"en_US_POSIX"];     [formatter setLocale:local];//需要配置地區,不然會造成模擬器正常,真機日期為null的情況     [formatter setTimeZone:timeZone];     [formatter setDateFormat:@"dd MMM yyyy HH:mm:ss"];//設定源時間字串的格式      NSDate* date = [formatter dateFromString:timeStr];//將源時間字串轉化為NSDate      NSLog(@"date--%@___class---%@",date,[date class]);    //可以自己再換格式,上面是源,下面是目標  //     NSDateFormatter* toformatter = [[NSDateFormatter alloc] init];//     [toformatter setDateStyle:NSDateFormatterMediumStyle];//     [toformatter setTimeStyle:NSDateFormatterShortStyle];//     [toformatter setDateFormat:@"yyyy/MM/dd HH:mm:ss"];//設定目標時間字串的格式//     NSString *targetTime = [toformatter stringFromDate:date];//將時間轉化成目標時間字串//     NSDate* toDate = [formatter dateFromString:targetTime];//將源時間字串轉化為NSDate      return date;}

 

iOS擷取網路時間與轉換格式

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.