使用NSDateFormatter转换时间字符串时,默认的时区是系统时区,如我们使用一般都是北京时间(+8),
如果直接使用
- [dateFormatter dateFromString:@"2012-01-01 00:00:00"];
所以我们要先指定时区为GMT再转换,如下:
- static NSString *GLOBAL_TIMEFORMAT = @"yyyy-MM-dd HH:mm:ss";
- static NSString *GLOBAL_TIMEBASE = @"2012-01-01 00:00:00";
- NSTimeZone* localzone = [NSTimeZone localTimeZone];
- NSTimeZone* GTMzone = [NSTimeZone timeZoneForSecondsFromGMT:0];
- NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
- [dateFormatter setDateFormat:GLOBAL_TIMEFORMAT];
- [dateFormatter setTimeZone:GTMzone];
- NSDate *bdate = [dateFormatter dateFromString:GLOBAL_TIMEBASE];
- NSDate *day = [NSDate dateWithTimeInterval:3600 sinceDate:bdate];
- [dateFormatter setTimeZone:localzone];
- NSLog(@"CurrentTime = %@", [dateFormatter stringFromDate:day]);
还可以如下:
- NSTimeZone* localzone = [NSTimeZone localTimeZone];
- NSTimeZone* GTMzone = [NSTimeZone timeZoneForSecondsFromGMT:0];
- NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
- [dateFormatter setDateFormat:GLOBAL_TIMEFORMAT];
- [dateFormatter setTimeZone:GTMzone];
- NSDate *bdate = [dateFormatter dateFromString:GLOBAL_TIMEBASE];
- NSDate *day = [NSDate dateWithTimeInterval:(3600 + [localzone secondsFromGMT]) sinceDate:bdate];
- NSString *text = [dateFormatter stringFromDate:day];