如何倒计时 Swift

How to make a countdown to date Swift

我正面临制作一个计时器应用程序的困难,所以我想既然我解决了它,我就可以帮助其他面临问题的人。所以基本上这个应用程序从当前时间开始倒计时到特定日期。由于堆栈溢出允许 Q 和 A 格式,我希望可以帮助你。解释见评论。

这是我如何设法为特定 NSDate 创建倒数计时器的解决方案,因为 SO 允许 Q 和 A 风格的答案。

// 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

如果你面临着和我一样的挣扎,希望对你们有所帮助

这对我有用。 唯一让我困扰的是它并没有真正倒计时,因为用户必须刷新页面才能重新计数。当用户在 UITableView 上上下滚动单元格时,您可以看到它 "counting",因为单元格会刷新视图。 另一件事是我在 currentDate "GMT+2:00" 的 NSTimeZone 上,因为它适用于我的时间,但这只是因为我还没有弄清楚如何使用设备 NSTimeZone。

    let releaseDate = "2015-05-02'T'22:00:00:000Z"
    let futureDateFormatter = NSDateFormatter()
    futureDateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    let date: NSDate = futureDateFormatter.dateFromString(releaseDate!)!

    let currentDate = NSDate();
    let currentFormatter = NSDateFormatter();
    currentFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ss.SSSZ"
    currentFormatter.timeZone = NSTimeZone(abbreviation: "GMT+2:00")

    let diffDateComponents = NSCalendar.currentCalendar().components([NSCalendarUnit.Month, NSCalendarUnit.Day, NSCalendarUnit.Hour, NSCalendarUnit.Minute], fromDate: currentDate, toDate: date, options: NSCalendarOptions.init(rawValue: 0))

    let countdown = "\(diffDateComponents.month) m: \(diffDateComponents.day) d: \(diffDateComponents.hour) h: \(diffDateComponents.minute) min"

已清除 up/updated 已接受答案的最新 Swift 版本。

    // 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"

已使用计时器计算的倒计时和前导零字符串格式进行清理和更新。

    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)
    }