Swift Days/Hours/Minutes/Seconds 的倒数计时器标签

Swift countdown timer labels for Days/Hours/Minutes/Seconds

我正在创建一个倒计时计时器,它倒计时到 UIDatePicker 中设置的 NSDate。我有一个标签,上面显示了我们倒计时的日期,而且效果很好。

我还想添加的是剩余天数和当天剩余 hours/minutes/seconds 天数的标签(即永远不会超过 23/59/59)这就是我的内容我现在已经完成了,但它显然显示了整个倒计时的值。希望有人能帮我找出正确的逻辑。

let secondsLeft = sender.date.timeIntervalSinceDate(NSDate())
hoursLabel.text = String(secondsLeft % 3600)
minutesLabel.text = String((secondsLeft / 60) % 60)
secondsLabel.text = String(secondsLeft % 60)

我想我要找的是一些 swift 相当于 datetime class 你在 php

中得到的

看看 NSCalendar class。具体看方法 components:fromDate:toDate:options: 这让您可以获取 2 个日期并使用您指定的任何单位计算它们之间的差异。

它也是可本地化的,因此如果您使用当前日历而用户使用中文、希伯来语或阿拉伯语日历,那么计算将为您提供适合该日历的正确结果。

知道了 - Swift 2

let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Day, .Hour, .Minute, .Second], fromDate: NSDate(), toDate: sender.date, options: [])
daysLabel.text = String(components.day)
hoursLabel.text = String(components.hour)
minutesLabel.text = String(components.minute)
secondsLabel.text = String(components.second)

这是 Chris Byatt 的答案的 Swift 4 版本,也适合游乐场使用:

import UIKit

let calendar = Calendar.current
let now = Date()
let futureDate = Date.distantFuture

let components = calendar.dateComponents([.day, .hour, .minute, .second], from: now, to: futureDate)

let daysLabel = UILabel()
let hoursLabel = UILabel()
let minutesLabel = UILabel()
let secondsLabel = UILabel()

daysLabel.text = String(describing: components.day)
hoursLabel.text = String(describing: components.hour)
minutesLabel.text = String(describing: components.minute)
secondsLabel.text = String(describing: components.second)

print(components) // day: 723942 hour: 23 minute: 56 second: 0 isLeapMonth: false

// Bonus: here's an easy way to print grammatically correct labels based on numbers
if let seconds = components.second {
    let labelText = "\(seconds) \(seconds == 1 ? "second" : "seconds")"
    print(labelText) // 0 seconds, 1 second, 2 seconds, etc.
}