Swift timeInterval formatter
You can use NSDateComponentsFormatter
. From the
documentation:
An
NSDateComponentsFormatter
object takes quantities of time and formats them as a user-readable string. Use a date components formatter to create strings for your app’s interface.
Example:
let formatter = NSDateComponentsFormatter()
formatter.unitsStyle = .Full
formatter.allowedUnits = .CalendarUnitSecond | .CalendarUnitMinute | .CalendarUnitHour
let pickedDate = datePicker.dateValue
let now = NSDate()
let formattedTimeLeft = formatter.stringFromDate(now, toDate: pickedDate)!
// Example result : 1:06:50
There are some more output formats available, e.g.
.Abbreviated : 1h 6m 50s
.Short : 1 hr, 6 min, 50 secs
.Full : 1 hour, 6 minutes and 50 seconds
Update for Swift 4 and later:
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .full // or .short or .abbreviated
formatter.allowedUnits = [.second, .minute, .hour]
let pickedDate = datePicker.date
let now = Date()
let formattedTimeLeft = formatter.string(from: now, to: pickedDate)!