Swift - Integer conversion to Hours/Minutes/Seconds

后端 未结 23 1132
無奈伤痛
無奈伤痛 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:12

    Another way would be convert seconds to date and take the components i.e seconds, minutes and hour from date itself. This solution has limitation only till 23:59:59

    0 讨论(0)
  • 2020-11-28 02:14

    Swift 5 & String Response, In presentable format

    public static func secondsToHoursMinutesSecondsStr (seconds : Int) -> String {
          let (hours, minutes, seconds) = secondsToHoursMinutesSeconds(seconds: seconds);
          var str = hours > 0 ? "\(hours) h" : ""
          str = minutes > 0 ? str + " \(minutes) min" : str
          str = seconds > 0 ? str + " \(seconds) sec" : str
          return str
      }
    
    public static func secondsToHoursMinutesSeconds (seconds : Int) -> (Int, Int, Int) {
            return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
     }
    

    Usage:

    print(secondsToHoursMinutesSecondsStr(seconds: 20000)) // Result = "5 h 33 min 20 sec"
    
    0 讨论(0)
  • 2020-11-28 02:15

    In Swift 5:

        var i = 9897
    
        func timeString(time: TimeInterval) -> String {
            let hour = Int(time) / 3600
            let minute = Int(time) / 60 % 60
            let second = Int(time) % 60
    
            // return formated string
            return String(format: "%02i:%02i:%02i", hour, minute, second)
        }
    

    To call function

        timeString(time: TimeInterval(i))
    

    Will return 02:44:57

    0 讨论(0)
  • 2020-11-28 02:17

    Swift 4 I'm using this extension

     extension Double {
    
        func stringFromInterval() -> String {
    
            let timeInterval = Int(self)
    
            let millisecondsInt = Int((self.truncatingRemainder(dividingBy: 1)) * 1000)
            let secondsInt = timeInterval % 60
            let minutesInt = (timeInterval / 60) % 60
            let hoursInt = (timeInterval / 3600) % 24
            let daysInt = timeInterval / 86400
    
            let milliseconds = "\(millisecondsInt)ms"
            let seconds = "\(secondsInt)s" + " " + milliseconds
            let minutes = "\(minutesInt)m" + " " + seconds
            let hours = "\(hoursInt)h" + " " + minutes
            let days = "\(daysInt)d" + " " + hours
    
            if daysInt          > 0 { return days }
            if hoursInt         > 0 { return hours }
            if minutesInt       > 0 { return minutes }
            if secondsInt       > 0 { return seconds }
            if millisecondsInt  > 0 { return milliseconds }
            return ""
        }
    }
    

    useage

    // assume myTimeInterval = 96460.397    
    myTimeInteval.stringFromInterval() // 1d 2h 47m 40s 397ms
    
    0 讨论(0)
  • 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)
    }
    
    0 讨论(0)
  • 2020-11-28 02:18

    Building upon Vadian's answer, I wrote an extension that takes a Double (of which TimeInterval is a type alias) and spits out a string formatted as time.

    extension Double {
      func asString(style: DateComponentsFormatter.UnitsStyle) -> String {
        let formatter = DateComponentsFormatter()
        formatter.allowedUnits = [.hour, .minute, .second, .nanosecond]
        formatter.unitsStyle = style
        guard let formattedString = formatter.string(from: self) else { return "" }
        return formattedString
      }
    }
    

    Here are what the various DateComponentsFormatter.UnitsStyle options look like:

    10000.asString(style: .positional)  // 2:46:40
    10000.asString(style: .abbreviated) // 2h 46m 40s
    10000.asString(style: .short)       // 2 hr, 46 min, 40 sec
    10000.asString(style: .full)        // 2 hours, 46 minutes, 40 seconds
    10000.asString(style: .spellOut)    // two hours, forty-six minutes, forty seconds
    10000.asString(style: .brief)       // 2hr 46min 40sec
    
    0 讨论(0)
提交回复
热议问题