2017-08-02 76 views
2

我希望轉移到小時和分鐘,我不關心日期。但下面的代碼給了我一個錯誤的結果。我通過了「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

回答

5

使用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

相關問題