NSDate给出了错误的答案(Objective-C)

问题描述:

我希望转移到小时和分钟,我不关心日期。但下面的代码给了我一个错误的结果。我通过了“7879”秒,它应该与'02:11:19'交谈,但它返回10:11:20。我不知道哪里出了问题。NSDate给出了错误的答案(Objective-C)

enter image description here p.s.我注意到d值是8小时,所以我认为它是关于时区...但是当我添加代码formatter.timeZone = [NSTimeZone timeZoneWithName:@"Asia/Shanghai"];时,它返回了我相同的结果。

+0

尝试用'的NSDate *日期= [NSDate的日期]',并检查是否仍然得到错误的结果? –

+0

添加代码,以便我们可以跟踪问题。 – KKRocks

+0

什么是时间戳实际上?这是几秒钟的日期/小时? – adev

使用NSDateComponentsFormatter。

NSDateComponentsFormatter *dateComponentsFormatter = [[NSDateComponentsFormatter alloc] init]; 
dateComponentsFormatter.zeroFormattingBehavior = NSDateComponentsFormatterZeroFormattingBehaviorPad; 
dateComponentsFormatter.allowedUnits = (NSCalendarUnitHour | NSCalendarUnitMinute | NSCalendarUnitSecond); 
NSLog(@"%@", [dateComponentsFormatter stringFromTimeInterval:7879]); 

输出:

2:11:19 

斯威夫特3版

let dateComponentsFormatter = DateComponentsFormatter() 
dateComponentsFormatter.zeroFormattingBehavior = .pad 
dateComponentsFormatter.allowedUnits = ([.hour, .minute, .second]) 
print("\(String(describing: dateComponentsFormatter.string(from: 7879)))") 
+0

这看起来不错。 – adev