在Swift中添加和减去时间

时间:2015-11-03 23:34:34

标签: ios swift nstimer nstimeinterval

我在伪代码中写了一些,因为我不知道它的语法。我希望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)

}

2 个答案:

答案 0 :(得分:5)

假设您的部署目标是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()
        }
    }

}

答案 1 :(得分:2)

这将增加6个小时:

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

这将找到区别:

let difference = future.timeIntervalSinceDate(now)