直接看代码,有详细的注释可以知道具体怎么用:
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-04-20 16:54:42.286 date1[16557:6377276] date:2016-04-20 08:54:42 +0000
2016-04-20 16:54:42.287 date1[16557:6377276] outputDate:2016-04-20 16:54:42
2016-04-20 16:54:42.288 date1[16557:6377276] nowDate:2016-04-20 16:54:42 +0000
2016-04-20 16:54:42.288 date1[16557:6377276] outputNowDate:2016-04-21 00:54:42
希望你可以通过上面的代码,解决相差8个小时问题