我有一个(有点?)关于Swift中的时间转换的基本问题。
我有一个整数,我想转换成小时/分钟/秒。
示例:Int = 27005会给我:
7 Hours 30 Minutes 5 Seconds
我知道如何在PHP中做到这一点,但是,唉,swift不是PHP。
我有一个(有点?)关于Swift中的时间转换的基本问题。
我有一个整数,我想转换成小时/分钟/秒。
示例:Int = 27005会给我:
7 Hours 30 Minutes 5 Seconds
我知道如何在PHP中做到这一点,但是,唉,swift不是PHP。
当前回答
Swift 5 &字符串响应,在像样的格式
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)
}
用法:
print(secondsToHoursMinutesSecondsStr(seconds: 20000)) // Result = "5 h 33 min 20 sec"
其他回答
下面是Swift3中的另一个简单实现。
func seconds2Timestamp(intSeconds:Int)->String {
let mins:Int = intSeconds/60
let hours:Int = mins/60
let secs:Int = intSeconds%60
let strTimestamp:String = ((hours<10) ? "0" : "") + String(hours) + ":" + ((mins<10) ? "0" : "") + String(mins) + ":" + ((secs<10) ? "0" : "") + String(secs)
return strTimestamp
}
我已经构建了一个现有答案的mashup,以简化一切并减少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)"
}
用法:
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)")
}
打印:
00:01:40
斯威夫特5:
extension Int {
func secondsToTime() -> String {
let (h,m,s) = (self / 3600, (self % 3600) / 60, (self % 3600) % 60)
let h_string = h < 10 ? "0\(h)" : "\(h)"
let m_string = m < 10 ? "0\(m)" : "\(m)"
let s_string = s < 10 ? "0\(s)" : "\(s)"
return "\(h_string):\(m_string):\(s_string)"
}
}
用法:
let seconds : Int = 119
print(seconds.secondsToTime()) // Result = "00:01:59"
Neek的答案不正确。
这是正确的版本
func seconds2Timestamp(intSeconds:Int)->String {
let mins:Int = (intSeconds/60)%60
let hours:Int = intSeconds/3600
let secs:Int = intSeconds%60
let strTimestamp:String = ((hours<10) ? "0" : "") + String(hours) + ":" + ((mins<10) ? "0" : "") + String(mins) + ":" + ((secs<10) ? "0" : "") + String(secs)
return strTimestamp
}
最新代码:XCode 10.4 Swift 5
extension Int {
func timeDisplay() -> String {
return "\(self / 3600):\((self % 3600) / 60):\((self % 3600) % 60)"
}
}