【问题标题】:Format timer label to hours:minutes:seconds in Swift在 Swift 中将计时器标签格式化为小时:分钟:秒
【发布时间】:2016-02-05 03:15:04
【问题描述】:

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

这是我的一些代码:

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”分钟。等等

【问题讨论】:

标签: ios swift nstimer


【解决方案1】:

你的计算都是错误的。

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)

【讨论】:

  • 老板招式,敬! :D
【解决方案2】:

@rmaddy 的解决方案是准确的并回答了问题。但是,无论是问题还是解决方案都没有考虑到国际用户。我建议使用DateComponentsFormatter 并让框架处理计算和格式化。这样做可以让您的代码更不容易出错,并且更有利于未来的发展。

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

从那篇文章中提取,这是代码 sn-p,它将替换您当前用于进行计算的代码。为 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) 

【讨论】:

  • 好点,但是在某些情况下,maddy 的回答就足够了。例如,如果您只为一个本地化申请。
  • 很好的答案,我忘了怎么做。
  • 很好的答案。谢谢
  • @NathanHosselton 否,因为 OP 明确指出:“我问的是如何使用上面给出的 TimeString 函数更改时间格式。我不是要求另一种方式去做。”。使用 DateComponentsFormatter 是大多数人应该使用的,但这不是 OP 想要的。
  • 对于来自 Google 的人:上面的答案不再有效。不确定 API 是否更改或一开始是否错误,但要修复它,请不要将持续时间传递给格式化程序。您需要通过DateComponents。请参阅此帖子以获得更清晰的信息:nshipster.com/formatter/#datecomponentsformatter
【解决方案3】:

Swift5

var totalSecond = Int()
var timer:Timer?

根据需求调用 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)
}

完成

【讨论】:

    【解决方案4】:

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

    【讨论】:

      【解决方案5】:

      声明变量小时、分钟和秒,然后复制粘贴下面的代码,它可以正常工作。

            if counter > 0 {
      
              let hours = counter / 3600
      
              let minutes = counter / 60
      
              let seconds = counter % 60
      
              counter = counter - 1
      
              timerLbl.text = "\(hours):\(minutes):\(seconds)"
      
          }
      

      【讨论】:

      • 虽然这可能会回答作者的问题,但它缺少一些解释性文字和/或文档链接。如果没有围绕它们的一些短语,原始代码 sn-ps 并不是很有帮助。您可能还会发现how to write a good answer 非常有帮助。请编辑您的答案。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-10-16
      • 1970-01-01
      • 1970-01-01
      • 2015-10-01
      • 1970-01-01
      相关资源
      最近更新 更多