Swift - Integer conversion to Hours/Minutes/Seconds

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

    Here is a more structured/flexible approach: (Swift 3)

    struct StopWatch {
    
        var totalSeconds: Int
    
        var years: Int {
            return totalSeconds / 31536000
        }
    
        var days: Int {
            return (totalSeconds % 31536000) / 86400
        }
    
        var hours: Int {
            return (totalSeconds % 86400) / 3600
        }
    
        var minutes: Int {
            return (totalSeconds % 3600) / 60
        }
    
        var seconds: Int {
            return totalSeconds % 60
        }
    
        //simplified to what OP wanted
        var hoursMinutesAndSeconds: (hours: Int, minutes: Int, seconds: Int) {
            return (hours, minutes, seconds)
        }
    }
    
    let watch = StopWatch(totalSeconds: 27005 + 31536000 + 86400)
    print(watch.years) // Prints 1
    print(watch.days) // Prints 1
    print(watch.hours) // Prints 7
    print(watch.minutes) // Prints 30
    print(watch.seconds) // Prints 5
    print(watch.hoursMinutesAndSeconds) // Prints (7, 30, 5)
    

    Having an approach like this allows the adding of convenience parsing like this:

    extension StopWatch {
    
        var simpleTimeString: String {
            let hoursText = timeText(from: hours)
            let minutesText = timeText(from: minutes)
            let secondsText = timeText(from: seconds)
            return "\(hoursText):\(minutesText):\(secondsText)"
        }
    
        private func timeText(from number: Int) -> String {
            return number < 10 ? "0\(number)" : "\(number)"
        }
    }
    print(watch.simpleTimeString) // Prints 07:30:05
    

    It should be noted that purely Integer based approaches don't take leap day/seconds into account. If the use case is dealing with real dates/times Date and Calendar should be used.

提交回复
热议问题