Swift - Integer conversion to Hours/Minutes/Seconds

后端 未结 23 1206
無奈伤痛
無奈伤痛 2020-11-28 01:47

I have a (somewhat?) basic question regarding time conversions in Swift.

I have an integer that I would like converted into Hours / Minutes / Second

23条回答
  •  情深已故
    2020-11-28 02:18

    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)
    }
    

提交回复
热议问题