Minhal Khan Minhal Khan - 4 months ago 10
Swift Question

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
?

Answer

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"