如何在 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 的差值。

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...