Swift中的加减时间 [英] Adding and Subtracting times in Swift
本文介绍了Swift中的加减时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我用伪代码编写了其中一些内容,因为我不知道其语法.我想让timeLeftLabel.text
反映出直到6个小时结束还剩多少小时,分钟和几秒钟.我最大的问题是我不知道如何增加和减少时间.谁能帮我吗?
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)
}
推荐答案
假设您的部署目标是iOS 8.0或更高版本,则应使用NSDateComponentsFormatter
设置字符串格式.您想要这样的东西:
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()
}
}
}
这篇关于Swift中的加减时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文