2016-02-05 91 views
10

我有DOWN 2小時計數直到0.格式計時器標籤小時:分鐘:秒夫特

這裏一個NSTimer是我的一些代碼:

var timer = NSTimer() 
let timeInterval:NSTimeInterval = 0.5 
let timerEnd:NSTimeInterval = 0.0 
var timeCount:NSTimeInterval = 7200.0 // seconds or 2 hours 

// TimeString Function 

func timeString(time:NSTimeInterval) -> String { 
    let minutes = Int(time)/60 
    let seconds = time - Double(minutes) * 60 
    let secondsFraction = seconds - Double(Int(seconds)) 
    return String(format:"%02i:%02i.%01i",minutes,Int(seconds),Int(secondsFraction * 10.0)) 
} 

定時器標籤是:

TimerLabel.text = "Time: \(timeString(timeCount))" 

然而,我的定時器標籤顯示爲:

Time: 200:59.0 

我如何格式化我的定時器標籤看起來像這樣:

Time: 01:59:59 // (which is hours:minutes:seconds)? 

[請注意,我有我的倒計時器沒有問題,我只需要知道如何使用TimeString以功能來更改時間格式。]

編輯: 有人提到我的問題是這個可能的重複:Swift - iOS - Dates and times in different format。但是,我在問如何使用上面給出的TimeString函數更改時間格式。我不是要求另一種方式來說明如何去做。

例如:

let minutes = Int(time)/60 

給了我 「200」 分鐘。等等。

+2

的可能的複製[夫特 - IOS - 日期和時間在不同格式(http://stackoverflow.com/questions/28489227/swift-ios-dates-and-times-in -different-format) – Abhijeet

+0

你的小時計算在哪裏? – rmaddy

+1

@Abhijeet這甚至不是很接近這個問題的重複。這個問題不涉及'NSDate',這個問題的解決方案與'NSDateFormatter'無關。 – rmaddy

回答

52

你的計算都是錯誤的。

let hours = Int(time)/3600 
let minutes = Int(time)/60 % 60 
let seconds = Int(time) % 60 
return String(format:"%02i:%02i:%02i", hours, minutes, seconds) 
14

@ rmaddy的解決方案是準確的,並回答了問題。但是,問題和解決方案都不考慮國際用戶。我建議使用DateComponentsFormatter並讓框架處理計算和格式。這樣做會使您的代碼更容易出錯,並且可以提供更多的未來證明

我碰到這個博客帖子提供了一個簡潔的解決方案來: http://crunchybagel.com/formatting-a-duration-with-nsdatecomponentsformatter/

從後拉,這是代碼片段將取代您目前使用,使您的計算代碼。更新的夫特3:

let duration: TimeInterval = 7200.0 

let formatter = DateComponentsFormatter() 
formatter.unitsStyle = .positional // Use the appropriate positioning for the current locale 
formatter.allowedUnits = [ .hour, .minute, .second ] // Units to display in the formatted string 
formatter.zeroFormattingBehavior = [ .pad ] // Pad with zeroes where appropriate for the locale 

let formattedDuration = formatter.string(from: duration) 
+0

好點,但是在某些情況下,maddy的回答就夠了。例如,如果您只爲一個本地化應用程序。 – Markus

+1

很好的回答,我忘記了如何做到這一點。 –

相關問題