Swift countdown timer- displays days hours seconds remaining

jss0199 picture jss0199 · Feb 9, 2016 · Viewed 7.9k times · Source

Hello I am very new to swift and I was trying to create an app that counts down to an event on a specific date. I want it to show the number of days hours and seconds left until the specified date but I cannot figure out how to do this.

Please help!

Answer

Marcelo dos Santos picture Marcelo dos Santos · Jun 25, 2018

Swift 4

var releaseDate: NSDate?
var countdownTimer = Timer()

func startTimer() {

    let releaseDateString = "2018-09-16 08:00:00"
    let releaseDateFormatter = DateFormatter()
    releaseDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    releaseDate = releaseDateFormatter.date(from: releaseDateString)! as NSDate

    countdownTimer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(updateTime), userInfo: nil, repeats: true)
}

@objc func updateTime() {

    let currentDate = Date()
    let calendar = Calendar.current

    let diffDateComponents = calendar.dateComponents([.day, .hour, .minute, .second], from: currentDate, to: releaseDate! as Date)

    let countdown = "Days \(diffDateComponents.day ?? 0), Hours \(diffDateComponents.hour ?? 0), Minutes \(diffDateComponents.minute ?? 0), Seconds \(diffDateComponents.second ?? 0)"

    print(countdown)
}