Erik Erik - 6 months ago 57
Swift Question

Find difference in seconds between NSDates as integer using Swift

I'm writing a piece of code where I want to time how long a button was held down. To do that I recorded an

when the button was pressed, and tried using the
function when the button was released. That seems to work but I can't find any way to print the result or switch it to an integer.

var timeAtPress = NSDate()

@IBAction func pressed(sender: AnyObject) {
timeAtPress = NSDate()

@IBAction func released(sender: AnyObject) {
var elapsedTime = NSDate.timeIntervalSinceDate(timeAtPress)
duration = ???

I've seen a few similar questions, but I don't know C so I had a hard time understanding the answers given. If there is a more efficient way to find out how long the button was held down I'm open to suggestions. Thanks in advance.

Rob Rob

Your attempt to calculate elapsedTime is incorrect. Im Swift 2, it would be:

let elapsed = NSDate().timeIntervalSinceDate(timeAtPress)

Or, in Swift 3:

let elapsed = Date().timeIntervalSince(timeAtPress)

Note the () after the NSDate reference. The NSDate()/Date() instantiates a new date object, and then timeIntervalSinceDate returns the time difference between that and timeAtPress. That will return a floating point value (technically, a NSTimeInterval/TimeInterval).

If you want that as truncated to a Int value, you can just use:

let duration = Int(elapsed)

And, BTW, your definition of the timeAtPress variable doesn't need to instantiate a NSDate object. I presume you intended:

var timeAtPress: NSDate!  // use `Date!` in Swift 3

That defines the variable as a NSDate variable (an implicitly unwrapped one), but you'd presumably defer the actual instantiation of that variable until pressed is called.

Alternatively, I often use CFAbsoluteTimeGetCurrent(), e.g.,

var start: CFAbsoluteTime!

And when I want to set startTime, I do the following:

start = CFAbsoluteTimeGetCurrent()

And when I want to calculate the number of seconds elapsed, I do the following:

let elapsed = CFAbsoluteTimeGetCurrent() - start