1. 程式人生 > >NSDateFormatter轉換時間字串時的時區問題

NSDateFormatter轉換時間字串時的時區問題

使用NSDateFormatter轉換時間字串時,預設的時區是系統時區,如我們使用一般都是北京時間(+8),

如果直接使用

[cpp] view plaincopyprint?
  1. [dateFormatter dateFromString:@"2012-01-01 00:00:00"];  
你會發現實際轉換為2011-12-31 16:00:00,少了8小時

所以我們要先指定時區為GMT再轉換,如下:

[cpp] view plaincopyprint?
  1. static NSString *GLOBAL_TIMEFORMAT = @"yyyy-MM-dd HH:mm:ss";  
  2. static
     NSString *GLOBAL_TIMEBASE = @"2012-01-01 00:00:00";  
  3.     NSTimeZone* localzone = [NSTimeZone localTimeZone];  
  4.     NSTimeZone* GTMzone = [NSTimeZone timeZoneForSecondsFromGMT:0];  
  5.     NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];  
  6.     [dateFormatter setDateFormat:GLOBAL_TIMEFORMAT];  
  7.     [dateFormatter setTimeZone:GTMzone];  
  8.     NSDate *bdate = [dateFormatter dateFromString:GLOBAL_TIMEBASE];  
  9.     NSDate *day = [NSDate dateWithTimeInterval:3600 sinceDate:bdate];  
  10.     [dateFormatter setTimeZone:localzone];  
  11.     NSLog(@"CurrentTime = %@", [dateFormatter stringFromDate:day]);  


還可以如下:

[cpp] view plaincopyprint?
  1. NSTimeZone* localzone = [NSTimeZone localTimeZone];  
  2. NSTimeZone* GTMzone = [NSTimeZone timeZoneForSecondsFromGMT:0];  
  3. NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];  
  4. [dateFormatter setDateFormat:GLOBAL_TIMEFORMAT];  
  5. [dateFormatter setTimeZone:GTMzone];  
  6. NSDate *bdate = [dateFormatter dateFromString:GLOBAL_TIMEBASE];  
  7. NSDate *day = [NSDate dateWithTimeInterval:(3600 + [localzone secondsFromGMT]) sinceDate:bdate];  
  8. NSString *text = [dateFormatter stringFromDate:day];