Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make a countdown to date Swift

Tags:

swift

timer

I was facing the struggle of making a timer app, so I thought that now that I solved it I could help others who face the problem. So basically this app counts down to a specific date from the current time. As stack overflow allows a Q and A format I hope that can help you. See the comments for explanations.

like image 545
Julian E. Avatar asked Nov 27 '22 04:11

Julian E.


1 Answers

Cleaned up and updated with countdown computed on a timer and leading zero String format.

    let futureDate: Date = {
        var future = DateComponents(
            year: 2020,
            month: 1,
            day: 1,
            hour: 0,
            minute: 0,
            second: 0
        )
        return Calendar.current.date(from: future)!
    }()

    var countdown: DateComponents {
        return Calendar.current.dateComponents([.day, .hour, .minute, .second], from: Date(), to: futureDate)
    }

    @objc func updateTime() {
        let countdown = self.countdown //only compute once per call
        let days = countdown.day!
        let hours = countdown.hour!
        let minutes = countdown.minute!
        let seconds = countdown.second!
        countdownLabel.text = String(format: "%02d:%02d:%02d:%02d", days, hours, minutes, seconds)
    }

    func runCountdown() {
        Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
    }
like image 94
ModerateEffort Avatar answered Dec 05 '22 09:12

ModerateEffort