您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 調試踩坑:NSDate 轉字符串時多出或少掉 8 小時怎麼辦

編輯:iOS 開發綜合

處理日期與字符串互轉時,時區問題是最容易踩的坑。最常見的現象就是轉出來的時間莫名多了或少了 8 個小時。下面分別說明兩種情況的成因與解法。

情況一:轉換後多了 8 小時

 - (NSString*)dateAsString:(NSDate*)date { NSTimeZone *timeZone=[NSTimeZone timeZoneWithName:@"UTC"]; NSDateFormatter *formatter=[[NSDateFormatter alloc] init]; [formatter setDateFormat:@"yyyy-MM-dd HH:mm"]; [formatter setTimeZone:timeZone]; NSString * timeString = [formatter stringFromDate:date]; return timeString; }

用法:timeString = [self dateAsString:date];

原因:無論系統採用 12 小時制還是 24 小時制,yyyy-MM-dd HH:mm:ss 返回的都是 24 小時制。把 TimeZone 顯式設置為 UTC,就能避免轉換時出現 8 小時偏差。

情況二:轉換後少了 8 小時

 - (NSString*)dateAsString:(NSDate*)date { NSDateFormatter *formatter=[[NSDateFormatter alloc]init]; formatter.dateFormat=@"yy-MM-dd HH:mm:ss"; NSString *timeStr=[formatter stringFromDate:date]; NSTimeZone *timeZone=[NSTimeZone systemTimeZone]; NSInteger seconds=[timeZone secondsFromGMTForDate:date]; NSDate *newDate=[date dateByAddingTimeInterval:seconds]; NSString *newTimeStr=[formatter stringFromDate:newDate]; return newTimeStr; }

用法:timeString = [self dateAsString:date];

這種寫法通過取出當前時區相對於 GMT 的偏移秒數,再把這個偏移量加回到日期上,從而校正出本地時間。掌握時區與偏移量的關係,是徹底擺脫 8 小時困擾的關鍵。

  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved