Swift 中的加减次数

Adding and Subtracting times in Swift

我已经用伪代码编写了其中一些内容,因为我不知道它的语法。我想让 timeLeftLabel.text 反映在 6 小时结束之前还剩下多少小时、分钟和秒。我最大的问题是我不知道如何加减时间。谁能帮帮我?

var timer = NSTimer()

func timerResults() {
    let theDate = NSDate()
    var endTime = theDate //+ 6 hours
    let timeLeft = endTime //- theDate
    timeLeftLabel.text = "\(timeLeft)"
}

@IBOutlet weak var timeLeftLabel: UILabel!
@IBAction func IBbtnUpdateTap(sender: UIButton){

timer = NSTimer.scheduledTimerWithTimeInterval(1.0, target: self, selector: Selector("timerResults"), userInfo: nil, repeats: true)

}

这将增加 6 小时:

let future = now.dateByAddingTimeInterval(3600*6) // 1 hour is 3600 seconds

这样就可以找到区别了:

let difference = future.timeIntervalSinceDate(now)

假设您的部署目标是 iOS 8.0 或更高版本,您应该使用 NSDateComponentsFormatter 来格式化您的字符串。你想要这样的东西:

class MyViewController : UIViewController {

    @IBOutlet weak var timeLeftLabel: UILabel!

    var targetDate: NSDate?
    var labelUpdateTimer: NSTimer?
    var timeLeftFormatter: NSDateComponentsFormatter?

    @IBAction func startTimerButtonWasTapped() {
        targetDate = NSDate(timeIntervalSinceNow: 6 * 60 * 60)
        labelUpdateTimer = NSTimer.scheduledTimerWithTimeInterval(1,
            target: self, selector: "labelUpdateTimerDidFire:", userInfo: nil, repeats: true)
        timeLeftFormatter = NSDateComponentsFormatter()
        timeLeftFormatter?.unitsStyle = .Abbreviated // gives e.g. "1h 20m 34s"
            // You might prefer .Positional, which gives e.g. "1:20:34"
        timeLeftFormatter?.allowedUnits = [ .Hour, .Minute, .Second ]

        labelUpdateTimerDidFire(labelUpdateTimer!)
    }

    @objc func labelUpdateTimerDidFire(timer: NSTimer) {
        let now = NSDate()
        timeLeftLabel.text = timeLeftFormatter!.stringFromDate(now,
            toDate: targetDate!)
        if now.compare(targetDate!) != NSComparisonResult.OrderedAscending {
            print("times up!")
            labelUpdateTimer?.invalidate()
        }
    }

}