twigofa twigofa - 5 months ago 47
Swift Question

How to find the time span between two times?

I want to calculate a remaining time. I have a finish time. How can I calculate the time remaining between now and finish time?

I need something like that

let date = NSDate()
let formatter = NSDateFormatter()
formatter.timeStyle = .ShortStyle
var now = formatter.stringFromDate(date) //prints 12.21 AM
var finishTime = "13:30 PM"

var remaining = now - finishTime //I want it to print 01:09 as remaining time

Sen Sen
Answer
let finishDate = NSDate() // or your date variable
let secondsFromNowToFinish = finishDate.timeIntervalSinceNow
let hours = Int(secondsFromNowToFinish / 3600)
let minutes = Int((secondsFromNowToFinish - Double(hours) * 3600) / 60)
let seconds = Int(secondsFromNowToFinish - Double(hours) * 3600 - Double(minutes) * 60 + 0.5)
Comments