我想出了如何在“hh:mm:ss”(下面的代码)中显示实时当前时间。我希望标签显示到特定目标时间为止的剩余时间,例如倒计时。我希望它倒计时直到例如每天下午 3 点,然后重新开始。我知道我需要从当前时间减去我的目标时间,但我不知道该怎么做。
(我是编程新手)
class ViewController: UIViewController {
@IBOutlet weak var Label: UILabel!
var timer = Timer()
override func viewDidLoad() {
super.viewDidLoad()
getCurrentTime()
}
private func getCurrentTime() {
timer = Timer.scheduledTimer(timeInterval: 0.1, target: self, selector:#selector(self.currentTime) , userInfo: nil, repeats: true)
}
@objc func currentTime() {
let formatter = DateFormatter()
formatter.dateFormat = "hh:mm:ss"
Label.text = formatter.string(from: Date())
}
}
最佳答案
使用 timeIntervalSince
查找两个日期之间的时间间隔。如下图
let secondsBetween: TimeInterval = targetDate.timeIntervalSince(currentDate)
self.counter = Int(secondsBetween)
func timerAction() {
counter -= 1
label.text = timeString(time: TimeInterval(counter))
}
关于ios - 如何从目标时间中减去当前时间?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58135985/