我有一个(有点?)关于Swift的时间转换的基本问题.
我有一个整数,我想将其转换为小时/分钟/秒.
Example: Int = 27005
会给我:
7 Hours 30 Minutes 5 Seconds
我知道如何在PHP中实现这一点,但唉,swift不是PHP:-)
任何关于我如何在快速实现这一点的提示都将是非常棒的! 提前谢谢您!
我有一个(有点?)关于Swift的时间转换的基本问题.
我有一个整数,我想将其转换为小时/分钟/秒.
Example: Int = 27005
会给我:
7 Hours 30 Minutes 5 Seconds
我知道如何在PHP中实现这一点,但唉,swift不是PHP:-)
任何关于我如何在快速实现这一点的提示都将是非常棒的! 提前谢谢您!
定义
func secondsToHoursMinutesSeconds(_ seconds: Int) -> (Int, Int, Int) {
return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
}
使用
> secondsToHoursMinutesSeconds(27005)
(7,30,5)
或
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 或 can access individual tuple members, if need be.
If you actually need to print it out with the w或ds 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()
w或ks f或 Int
arguments. If you want a Double
version you'll need to decide what the return values are - could be (Int, Int, Double)
或 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)
}