Swift – Integer conversion to Hours/Minutes/Seconds

Define

func secondsToHoursMinutesSeconds(_ seconds: Int) -> (Int, Int, Int) {
    return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
}

Use

> secondsToHoursMinutesSeconds(27005)
(7,30,5)

or

let (h,m,s) = secondsToHoursMinutesSeconds(27005)

The above function makes use of Swift tuples to return three values at once. You destructure the tuple using the let (var, ...) syntax or can access individual tuple members, if need be.

If you actually need to print it out with the words Hours etc then use something like this:

func printSecondsToHoursMinutesSeconds(_ seconds: Int) {
  let (h, m, s) = secondsToHoursMinutesSeconds(seconds)
  print ("\(h) Hours, \(m) Minutes, \(s) Seconds")
}

Note that the above implementation of secondsToHoursMinutesSeconds() works for Int arguments. If you want a Double version you’ll need to decide what the return values are – could be (Int, Int, Double) or could be (Double, Double, Double). You could try something like:

func secondsToHoursMinutesSeconds(seconds: Double) -> (Double, Double, Double) {
  let (hr,  minf) = modf(seconds / 3600)
  let (min, secf) = modf(60 * minf)
  return (hr, min, 60 * secf)
}

Leave a Comment