*I have two dates. Those, I have to do date format in UTC and after that have to do subtraction of two dates. I have to run timer for remaining time. And once its reaches 0 second, I have to stop timer and I have to call some api.
fromDate: 2021-07-21T09:04:38.306Z, toDate: 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 } But, Always its printing as 0d :0h : 0: 0 And its not showing seconds, minutes Its printing like below always
2021-07-21 11:14:23 +0000 2021-07-21 11:14:23 +0000 0d :0h : 0: 0 Any Suggestions?*
dateFormatter.date(from:)is returning nil. Try changing ourdateFormatter.dateFormatto "yyyy-MM-dd'T'HH:mm:ss.SSSZ"dateFormatter.date(from: "\(unlockTime)")is returing nil.