How to make a countdown to date Swift

前端 未结 4 480
青春惊慌失措
青春惊慌失措 2021-02-03 16:03

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

4条回答
  •  执笔经年
    2021-02-03 16:42

    Cleaned up/updated for latest Swift version of the accepted answer.

        // here we set the current date
    
        let date = NSDate()
        let calendar = Calendar.current
    
        let components = calendar.dateComponents([.hour, .minute, .month, .year, .day], from: date as Date)
    
        let currentDate = calendar.date(from: components)
    
        let userCalendar = Calendar.current
    
        // here we set the due date. When the timer is supposed to finish
        let competitionDate = NSDateComponents()
        competitionDate.year = 2017
        competitionDate.month = 4
        competitionDate.day = 16
        competitionDate.hour = 00
        competitionDate.minute = 00
        let competitionDay = userCalendar.date(from: competitionDate as DateComponents)!
    
        //here we change the seconds to hours,minutes and days
        let CompetitionDayDifference = calendar.dateComponents([.day, .hour, .minute], from: currentDate!, to: competitionDay)
    
    
        //finally, here we set the variable to our remaining time
        let daysLeft = CompetitionDayDifference.day
        let hoursLeft = CompetitionDayDifference.hour
        let minutesLeft = CompetitionDayDifference.minute
    
        print("day:", daysLeft ?? "N/A", "hour:", hoursLeft ?? "N/A", "minute:", minutesLeft ?? "N/A")
    
        //Set countdown label text
        countDownLabel.text = "\(daysLeft ?? 0) Days, \(hoursLeft ?? 0) Hours, \(minutesLeft ?? 0) Minutes"
    

提交回复
热议问题