Minhal Khan
Minhal Khan

Reputation: 321

Find minutes remaining between two times

I have two times in the format HH:MM how would I compare the second from the first one finding how many minutes left until I reach to the first time:

example:

timeOne = 12:01
timeTwo = 11:32
output = 29 minutes

Any help writing this in Swift?

Upvotes: 1

Views: 1105

Answers (2)

Anurag
Anurag

Reputation: 141869

NSCalendar can diff dates easily (assuming start and end are NSDate instances

let calendar = NSCalendar.currentCalendar()
let components = calendar.components(.Minute, fromDate: start, toDate: end, options: [])

components.minute

If you are interested in getting just the formatted string, and not the actual value, then checkout NSDateComponentsFormatter:

let formatter = NSDateComponentsFormatter()
formatter.allowedUnits = .Minute
formatter.unitsStyle = .SpellOut
// includesTimeRemainingPhrase gives strings like "T minutes remaining"

formatter.stringFromDate(start, toDate: end)

By changing the unitsStyle, you could get different representations, such as:

"54m"
"54 minutes"
"54 min"
"fifty-four minutes"

Upvotes: 4

Evgeny Karkan
Evgeny Karkan

Reputation: 9612

You should operate with 2 NSDate instances, then you may use next API:

let interval = laterDate.timeIntervalSinceDate(earlierDate)

It returns the number of seconds, as an NSTimeInterval value. Divide it by 60 will give you minutes.

Upvotes: 3

Related Questions