I'm trying to make a timer show the following - years : months : weeks : days : hours : minutes : seconds : milliseconds.
I don't want it to show the minutes until the seconds reaches 60, and the same for hours days etc. For example: If it's holding at 3 days 4 hours 39 min 3 seconds and 43 milliseconds, it shouldn't show the months or years because they would both be 0 so far.
Here is what I have.
@IBOutlet weak var timeLabel: UILabel!
var timerCount = 0
var timerRuning = false
var timer = NSTimer()
func counting() {
timerCount++
timeLabel.text = "\(timerCount)"
}
@IBAction func startTime(sender: UIButton)
{
if timerRuning == false {
timer = NSTimer.scheduledTimerWithTimeInterval(1, target: self, selector: ("counting"), userInfo: nil, repeats: true)
timerRuning = true
}
}
@IBAction func finishTime(sender: UIButton)
{
if timerRuning == true {
timer.invalidate()
timerRuning = false
}
}
The problem is it only shows seconds. How can I get it to show all the rest? (Like I wrote above.)
There is a new class NSDateComponentsFormatter
introduced in iOS 8.0 which can format an amount of seconds to readable time strings.
func counting() {
timerCount++
let formatter = NSDateComponentsFormatter()
formatter.unitsStyle = .Full
timeLabel.text = formatter.stringFromTimeInterval(NSTimeInterval(timerCount))
}
But there is one restriction: It doesn't consider units less than seconds.