do it better
do it better

Reputation: 4807

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

Upvotes: 3

Views: 4327

Answers (2)

shim
shim

Reputation: 10116

The correct and ultimately much simpler solution, and handles localization and things like leap seconds / days properly, is to use NSDateComponentsFormatter.

let formatter = DateComponentsFormatter()
formatter.zeroFormattingBehavior = .pad
formatter.allowedUnits = [.hour, .minute, .second]

print(formatter.string(from: 200.0)!)

Outputs "0:03:20"

This is a Swift version of this Objective C answer.

There are lots of different options that you can see in the documentation in case you want something more like "About 3 seconds remaining", abbreviations, more units like years/months/days etc.

Upvotes: 2

ukim
ukim

Reputation: 2465

func timeRemainingString(finishDate date:NSDate) -> String {
    let secondsFromNowToFinish = date.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)

    return String(format: "%02d:%02d:%02d", hours, minutes, seconds)
}

Upvotes: 6

Related Questions