[英]How to run timer for two dates subtraction in Swift
*我有两个约会。 那些,我必须在UTC中做日期格式,然后必须做两个日期的减法。 我必须为剩余时间运行计时器。 一旦达到 0 秒,我就必须停止计时器,并且必须调用一些 api。
从日期:2021-07-21T09:04:38.306Z,到日期:2021-07-21T09:06:08.000Z
override func viewDidLoad() {
super.viewDidLoad()
let when = DispatchTime.now() + 0.1 // change 2 to desired number of seconds
DispatchQueue.main.asyncAfter(deadline: when) {
self.countDownTimer = Timer.scheduledTimer(timeInterval: 1.0, target: self, selector: #selector(MyViewController.countDownTime), userInfo: nil, repeats: true)
}
}
@objc func countDownTime() {
let unlockDuration = self.getCountDownTime(currentTime: "2021-07-21T09:04:38.306Z" , unlockTime: "2021-07-21T09:06:08.000Z")
if unlockDuration == "0d :0h : 0: 0" {
self.stopTimer()
}
}
func stopTimer(){
guard self.countDownTimer != nil else {
fatalError("No timer active, start the timer before you stop it.")
}
self.countDownTimer?.invalidate()
self.callAPI()
}
func getCountDownTime(currentTime: String, unLockTime: String) -> String {
let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ssZ"
dateFormatter.timeZone = TimeZone(abbreviation: "UTC")
let unlockDate = dateFormatter.date(from: "\(unlockTime)") ?? Date()
let currentDate = dateFormatter.date(from: "\(currentTime)") ?? Date()
print(currentDate)
print(unlockDate)
let calendar = Calendar.current
let diffDateComponents = calendar.dateComponents([.day, .hour, .minute, .second], from: unlockDate, to: currentDate)
let countdown = "\(String(describing:diffDateComponents.day!))d :\(String(describing: diffDateComponents.hour!))h : \(String(describing: diffDateComponents.minute!)): \(String(describing: diffDateComponents.second!))"
print(countdown)
return countdown
}
func callAPI() {
//Calling api here
}
但是,始终将其打印为 0d :0h : 0: 0 并且不显示秒,分钟它的打印始终如下所示
2021-07-21 11:14:23 +0000
2021-07-21 11:14:23 +0000
0d :0h : 0: 0
有什么建议么?*
要使用此格式解析日期:
2021-07-21T09:04:38.306Z
采用
dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
因为dateFormatter.date(from: "\\(unlockTime)")
返回 nil,所以你得到 0 的差异,所以你从Date()
减去Date()
并得到 0 差异。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.