微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何在 Swift 中为两个日期减法运行计时器

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。