Adding and Subtracting times in Swift

2020-03-24 02:35发布

问题:

I've written some of this in pseudo code because I don't know the syntax for it. I'd like to have the timeLeftLabel.text reflect how many hours, minutes, and seconds are left until the 6 hours are up. My biggest problem is that I don't know how to add and subtract times. Can anyone help me?

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)

}

回答1:

Assuming your deployment target is iOS 8.0 or later, you should use NSDateComponentsFormatter to format your string. You want something like this:

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

}


回答2:

This will add 6 hours:

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

This will find the difference:

let difference = future.timeIntervalSinceDate(now)