[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; }