在IOS中如果你直接使用[NSDate date]来获取时间,是不行的,因为这样获得的时间是GMT时间,也就是格林威治时间,与北京时间是相差8个小时的,那么怎么来获取标准时间呢?有下面两种方法。
①、使用formatter来格式化时间
代码实现:
1 NSDateFormatter *form = [[NSDateFormatter alloc] init];
2 [form setDateFormat:@"MM-dd-HH-mm"];
3 NSString *str = [form stringFromDate:date];
②、在GMT时间基础上加上8个小时
1 NSDate *date = [NSDate date];
2 NSTimeZone *zone = [NSTimeZone systemTimeZone];
3 NSInteger interval = [zone secondsFromGMTForDate:date];
4 NSDate *nowDate = [date dateByAddingTimeInterval:interval];
要注意的是,如果你使用第二种办法获得时间后,不能再去使用format去格式化时间,如果那样做的话又会比当前时间相差8个小时!
测试的代码:
1 //获取标准时间
2 NSDate *date = [NSDate date];
3 NSLog(@"直接使用NSDate获取的时间:%@", date);
4 //使用formatter格式化后的时间
5 NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
6 [formatter setDateFormat:@"yyyy-MM-dd HH-mm-ss"];
7 NSString *time_now = [formatter stringFromDate:date];
8 NSLog(@"格式化后的时间%@", time_now);
9 //在GMT时间上加上8个小时后的时间
10 NSTimeZone *zone = [NSTimeZone systemTimeZone];
11 NSInteger sec = [zone secondsFromGMTForDate:date];
12 NSDate *new_date = [date dateByAddingTimeInterval:sec];
13 NSLog(@"在GMT时间上加上时间差之后的时间:%@", new_date);
14
15 //如果在加上时间差后的时间上面再进行格式化的话,时间有误差
16 NSString *time_other = [formatter stringFromDate:new_date];
17 NSLog(@"加上时间差后再进行一次格式化后的时间:%@", time_other);
打印结果:
1 2016-05-21 17:56:42.593 ttttt[2206:156343] 直接使用NSDate获取的时间:2016-05-21 09:56:42 +0000
2 2016-05-21 17:56:42.594 ttttt[2206:156343] 格式化后的时间2016-05-21 17-56-42
3 2016-05-21 17:56:42.594 ttttt[2206:156343] 在GMT时间上加上时间差之后的时间:2016-05-21 17:56:42 +0000
4 2016-05-21 17:56:42.594 ttttt[2206:156343] 加上时间差后再进行一次格式化后的时间:2016-05-22 01-56-42
可以看到问题的存在了!