Swift - 整数转换为小时/分钟/秒 [英] Swift - Integer conversion to Hours/Minutes/Seconds
问题描述
我有一个(有点?)关于 Swift 中时间转换的基本问题。
I have a (somewhat?) basic question regarding time conversions in Swift.
我有一个整数,我想转换成小时/分钟/秒。
I have an integer that I would like converted into Hours / Minutes / Seconds.
示例: Int = 27005
会给我:
7 Hours 30 Minutes 5 Seconds
我知道如何在PHP中执行此操作,但唉,swift不是PHP: - )
I know how to do this in PHP, but alas, swift isn't PHP :-)
有关我如何能提示的任何提示在swift中实现这一点真是太棒了!
提前谢谢!
Any tips on how I can achieve this in swift would be fantastic! Thank you in advance!
推荐答案
定义
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)
上面的函数使用Swift元组一次返回三个值。您可以使用 let(var,...)
语法对元组进行解构,或者如果需要,可以访问单个元组成员。
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.
如果您确实需要使用 Hours
等字样打印出来,请使用以下内容:
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")
}
注意上面的实现 secondsToHoursMinutesSeconds()
适用于 Int
参数。如果你想要一个 Double
版本,你需要确定返回值是什么 - 可以是(Int,Int,Double)
或可能(双倍,双倍,双倍)
。您可以尝试类似:
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)
}
这篇关于Swift - 整数转换为小时/分钟/秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!