Swift倒计时器 - 显示剩余的天数小时

时间:2016-02-09 05:57:45

标签: swift timer countdown

您好我是swift的新手,我正在尝试创建一个可以计入特定日期事件的应用程序。我希望它显示在指定日期之前剩余的小时数和秒数,但我无法弄清楚如何执行此操作。

请帮忙!

4 个答案:

答案 0 :(得分:7)

这就像一个魅力:

var releaseDate: NSDate?

override func viewDidLoad() {
    super.viewDidLoad()

    let releaseDateString = "2016-03-02 22:00:00"
    let releaseDateFormatter = NSDateFormatter()
    releaseDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
    releaseDate = releaseDateFormatter.dateFromString(releaseDateString)!

    NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: "countDownDate", userInfo: nil, repeats: true)
}

func countDownDate() {
    let currentDate = NSDate()

    let diffDateComponents = NSCalendar.currentCalendar().components([NSCalendarUnit.Month, NSCalendarUnit.Day, NSCalendarUnit.Hour, NSCalendarUnit.Minute, NSCalendarUnit.Second], fromDate: currentDate, toDate: releaseDate!, options: .MatchFirst)

    let countdown = "Months: \(diffDateComponents.month), Days: \(diffDateComponents.day), Hours: \(diffDateComponents.hour), Minutes: \(diffDateComponents.minute), Seconds: \(diffDateComponents.second)"
    print(countdown)
}

答案 1 :(得分:4)

Swift 3

var releaseDate: Date? 

override func viewDidLoad() {
  super.viewDidLoad()     

  let releaseDateFormatter = DateFormatter()
  releaseDateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss"
  releaseDate = releaseDateFormatter.date(from:releaseDateString!)!

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

func countDownDate() {
    let date = Date()
    let calendar = Calendar.current

    let diffDateComponents = calendar.dateComponents([.day, .hour, .minute, .second], from: date, to: releaseDate!)
    let countdown = "Days \(diffDateComponents.day),  Hours: \(diffDateComponents.hour), Minutes: \(diffDateComponents.minute), Seconds: \(diffDateComponents.second)"
    print(countdown)
}

答案 2 :(得分:3)

快捷键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)
}

答案 3 :(得分:0)

这就是我必须为我的应用程序做的事情。

import UIKit
import Foundation

var timer = Timer()
var currentTime = Date()
var compareTime = Date().addingTimeInterval(-21600)


func setupButtonTitle()
{
   if UserDefaults.standard.object(forKey: "count6") == nil
   {
    button.setTitle("PRESS", for: .normal)
    button.backgroundColor = .green
   }
   else
   {
    button.setTitle("PRESS" + "\nIN " + "\(startTimer()))" , for: .normal)
   }
 button.addTarget(self, action: #selector(buttonTap), for: .touchUpInside)
}


func startTimer()
{
  timer = Timer.scheduledTimer(timeInterval: 1, target: self, selector: #selector(sixHourCountdown), userInfo: nil, repeats: true)
}

@objc func sixHourCountdown()
{
    let timeStarted = UserDefaults.standard.object(forKey: "count6")

    let timeStart = timeStarted as! Date
    let diffComponents = Calendar.current.dateComponents([.hour, .minute, .second], from: compareTime, to: timeStart)
    let hour = diffComponents.hour!
    let minute = diffComponents.minute!
    let second = diffComponents.second!
    let timeRemaining = String(format: "%02d:%02d:%02d", hour, minute, second)

    compareTime += 1

    if hour == 0 && minute == 0 && second == 0 || timeStart < compareTime
    {
        button.setTitle("PRESS", for: .normal)
        button.backgroundColor = .green
        timer.invalidate()
    }
    else
    {
        button.setTitle("PRESS IN" + "\n\(timeRemaining)", for: .normal)
    }
 }


@objc func buttonTap()
{
    if button.currentTitle != "PRESS"
    {
        button.backgroundColor = .red
        DispatchQueue.main.asyncAfter(deadline: .now() + .seconds(2), execute:
        {
         button.backgroundColor = .yellow
        })
    }
    if button.currentTitle == "PRESS" && button.backgroundColor == .green
    {
        UserDefaults.standard.set(currentTime, forKey: "count6")

        let otherVC = OTHERVC()
        self.navigationController?.pushViewController(otherVC, animated: true)
    }
}


override func viewDidLoad() {
super.viewDidLoad()


setupButtonTitle()