[英]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.