NSDate相差8个小时问题

2018-05-17 15:59:38 浏览数 (1)

代码语言:javascript复制
NSDate * date = [NSDate date];

NSLog(@"date:%@", date);

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

[outputFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];

NSTimeZone * timezone = [NSTimeZone timeZoneForSecondsFromGMT:8 * 3600];//直接指定时区

[outputFormatter setTimeZone:timezone];//这里指定不指定时区并没有什么用

[outputFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSString * outputDate = [outputFormatter stringFromDate:date];

NSLog(@"outputDate:%@", outputDate);


//这里处理8个小时时间差问题,下面这三句可以解决相差8个小时问题
NSTimeZone * zone = [NSTimeZone systemTimeZone];

NSInteger interval = [zone secondsFromGMTForDate:date];

NSDate * nowDate = [date dateByAddingTimeInterval:interval];

NSLog(@"nowDate:%@", nowDate);

//所以,NSDate转字符串和直接使用NSDate的时候一定要注意,转字符串的时候不用处理差8个小时问题,直接用NSDate的时候需要处理相差8个小时的问题

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

[outputFormatter1 setDateFormat:@"yyyy-MM-dd HH:mm:ss"];

NSString * outputNowDate = [outputFormatter1 stringFromDate:nowDate];

NSLog(@"outputNowDate:%@", outputNowDate);

//使用outputFormatter输出的时候总是和NSDate相差8个小时

输出:2016-09-11 18:34:49.964

2016-09-11 18:34:49.973 Date[31220:253182]

date:2016-09-11 10:34:49 0000

2016-09-11 18:34:49.974 Date[31220:253182]

outputDate:2016-09-11 18:34:49

2016-09-11 18:34:49.974 Date[31220:253182]

nowDate:2016-09-11 18:34:49 0000

2016-09-11 18:34:49.974 Date[31220:253182]

outputNowDate:2016-09-12 02:34:49

0 人点赞