Swift - Integer conversion to Hours/Minutes/Seconds

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

    I have built a mashup of existing answers to simplify everything and reduce the amount of code needed for Swift 3.

    func hmsFrom(seconds: Int, completion: @escaping (_ hours: Int, _ minutes: Int, _ seconds: Int)->()) {
    
            completion(seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
    
    }
    
    func getStringFrom(seconds: Int) -> String {
    
        return seconds < 10 ? "0\(seconds)" : "\(seconds)"
    }
    

    Usage:

    var seconds: Int = 100
    
    hmsFrom(seconds: seconds) { hours, minutes, seconds in
    
        let hours = getStringFrom(seconds: hours)
        let minutes = getStringFrom(seconds: minutes)
        let seconds = getStringFrom(seconds: seconds)
    
        print("\(hours):\(minutes):\(seconds)")                
    }
    

    Prints:

    00:01:40

提交回复
热议问题