How to make a countdown to date Swift

前端 未结 4 482
青春惊慌失措
青春惊慌失措 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条回答
  •  闹比i
    闹比i (楼主)
    2021-02-03 16:44

    Here is the solution of how I managed to create a countdown timer to a specific NSDate, for SO allows Q and A Style Answers.

    // here we set the current date
    
     let date = NSDate()
        let calendar = NSCalendar.currentCalendar()
        let components = calendar.components(.CalendarUnitHour | .CalendarUnitMinute | .CalendarUnitMonth | .CalendarUnitYear | .CalendarUnitDay, fromDate: date)
        let hour = components.hour
        let minutes = components.minute
        let month = components.month
        let year = components.year
        let day = components.day
    
    
    
        let currentDate = calendar.dateFromComponents(components)
    
      // here we set the due date. When the timer is supposed to finish  
    
        let userCalendar = NSCalendar.currentCalendar()
    
    
        let competitionDate = NSDateComponents()
        competitionDate.year = 2015
        competitionDate.month = 6
        competitionDate.day = 21
        competitionDate.hour = 08
        competitionDate.minute = 00
        let competitionDay = userCalendar.dateFromComponents(competitionDate)!
    
    
    // Here we compare the two dates 
        competitionDay.timeIntervalSinceDate(currentDate!)
    
        let dayCalendarUnit: NSCalendarUnit = (.CalendarUnitDay | .CalendarUnitHour | .CalendarUnitMinute)
    
    //here we change the seconds to hours,minutes and days
        let CompetitionDayDifference = userCalendar.components(
            dayCalendarUnit, fromDate: currentDate!, toDate: competitionDay,
            options: nil)
      //finally, here we set the variable to our remaining time  
        var daysLeft = CompetitionDayDifference.day
        var hoursLeft = CompetitionDayDifference.hour
        var minutesLeft = CompetitionDayDifference.minute
    

    Hope that helps you guys if you're facing the same struggle as I have

提交回复
热议问题