ios 在 Swift 中将计时器标签格式化为小时:分钟:秒

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/35215694/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 08:25:20  来源:igfitidea点击:

Format timer label to hours:minutes:seconds in Swift

iosswiftnstimer

提问by mjoe7

I have an NSTimer which counts DOWN from 2 hours until 0.

我有一个 NSTimer,它从 2 小时倒数到 0。

Here are some of my code:

这是我的一些代码:

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))
}

The Timer Label is:

计时器标签是:

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

HOWEVER, my timer label shows as:

但是,我的计时器标签显示为:

Time: 200:59.0

How do I format my timer label to look like this:

如何将我的计时器标签格式化为如下所示:

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

[Please note that I have no problems with my countdown timer, I only need to know how to CHANGE THE TIME FORMAT using the TimeString function.]

[请注意,我的倒数计时器没有问题,我只需要知道如何使用 TimeString 函数更改时间格式。]

EDIT: Someone mentioned that my question is a possible duplicate of this one: Swift - iOS - Dates and times in different format. HOWEVER, I am asking on how do I change the time format using the TimeString function that I gave above. I am not asking for another WAY on how to do it.

编辑:有人提到我的问题可能是这个问题的重复:Swift - iOS - Dates and times in different format。但是,我问的是如何使用上面给出的 TimeString 函数更改时间格式。我不是在要求另一种方法来做到这一点。

For instance:

例如:

let minutes = Int(time) / 60

gives me "200" minutes. etc.

给我“200”分钟。等等。

回答by rmaddy

Your calculations are all wrong.

你的计算全错了。

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)

回答by Mark Suman

@rmaddy's solution is accurate and answers the question. However, neither the question nor the solution take into account international users. I suggest using DateComponentsFormatterand let the framework handle the calculations and formatting. Doing so makes your code less error prone and more future proof.

@rmaddy 的解决方案是准确的并回答了问题。然而,问题和解决方案都没有考虑到国际用户。我建议使用DateComponentsFormatter并让框架处理计算和格式。这样做可以使您的代码更不容易出错并且更具前瞻性。

I came across this blog post that provides a concise solution: http://crunchybagel.com/formatting-a-duration-with-nsdatecomponentsformatter/

我看到这篇博客文章提供了一个简洁的解决方案:http: //crunchybagel.com/formatting-a-duration-with-nsdatecomponentsformatter/

Pulled from that post, this is the code snippet that would replace the code you're currently using to make your calculations. Updated for Swift 3:

从那篇文章中提取的代码片段将替换您当前用于进行计算的代码。为 Swift 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) 

回答by Rohit Nishad

Swift5

斯威夫特5

var totalHour = Int()
var totalMinut = Int()
var totalSecond = Int()
var timer:Timer?

call startTimer() based on requirement-

根据要求调用 startTimer() -

func startTimer(){
timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(countdown), userInfo: nil, repeats: true)
}

@objc func countdown() {
    var hours: Int
    var minutes: Int
    var seconds: Int

    if totalSecond == 0 {
        timer?.invalidate()
    }
    totalSecond = totalSecond - 1
    hours = totalSecond / 3600
    minutes = (totalSecond % 3600) / 60
    seconds = (totalSecond % 3600) % 60
    timeLabel.text = String(format: "%02d:%02d:%02d", hours, minutes, seconds)
}

Done

完毕

回答by oscar castellon

The best way to implement a Timer in Swift (swift 4 works fine). Declare the variable secs: Int and assign the value, in seconds, of the timer. Then with the Timer () function, discount one second at a time and pass it to this function.

在 Swift 中实现 Timer 的最佳方法(swift 4 工作正常)。声明变量 secs: Int 并分配计时器的值(以秒为单位)。然后用Timer()函数,一次打折一秒,传给这个函数。

var secs = 0
var timer = Timer()

func startTimer(segs: Int) {
        seg = segs
        timer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(timerDiscount), userInfo: nil, repeats: true)
    }

func timerDiscount() {
            let hours = secs / 3600
            let mins = secs / 60 % 60
            let secs = secs % 60
            let restTime = ((hours<10) ? "0" : "") + String(hours) + ":" + ((mins<10) ? "0" : "") + String(mins) + ":" + ((secs<10) ? "0" : "") + String(secs)
}

I hope I can help who needs it.

希望能帮到有需要的人。

回答by Prashanth Thota

Declare the variables hours ,minutes and seconds and copy paste the below code it works fine.

声明变量 hours ,minutes 和 seconds 并复制粘贴下面的代码它工作正常。

      if counter > 0 {

        let hours = counter / 3600

        let minutes = counter / 60

        let seconds = counter % 60

        counter = counter - 1

        timerLbl.text = "\(hours):\(minutes):\(seconds)"

    }