Swift – 整数转换为小时/分钟/秒

我有一个关于Swift时间转换的基本问题。

我有一个整数,我想转换成小时/分钟/秒。

例如: 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) 

上面的函数使用Swift元组一次返回三个值。 使用let (var, ...)语法解构元组let (var, ...)或者可以访问单个元组成员(如果需要的话)。

如果你真的需要用Hours等打印出来,然后使用这样的东西:

 func printSecondsToHoursMinutesSeconds (seconds:Int) -> () { let (h, m, s) = secondsToHoursMinutesSeconds (seconds) print ("\(h) Hours, \(m) Minutes, \(s) Seconds") } 

请注意,上面的secondsToHoursMinutesSeconds()适用于Int参数。 如果你想要一个Double版本,你需要决定返回值是什么 – 可以是(Int, Int, Double)或者可以是(Double, Double, Double) 。 你可以尝试像这样:

 func secondsToHoursMinutesSeconds (seconds : Double) -> (Double, Double, Double) { let (hr, minf) = modf (seconds / 3600) let (min, secf) = modf (60 * minf) return (hr, min, 60 * secf) } 

在macOS 10.10+ / iOS 8.0+ (NS)DateComponentsFormatter中已经引入了(NS)DateComponentsFormatter来创build一个可读的string。

它考虑用户的语言环境和语言。

 let interval = 27005 let formatter = DateComponentsFormatter() formatter.allowedUnits = [.hour, .minute, .second] formatter.unitsStyle = .full let formattedString = formatter.string(from: TimeInterval(interval))! print(formattedString) 

可用的单位样式是positionalabbreviatedshortfullspellOutbrief

欲了解更多信息,请阅读文件 。

我已经构build了现有答案的混搭,以简化一切,并减lessSwift 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

这是一个更加结构化/灵活的方法:(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) 

有这样的方法可以添加便捷的parsing,如下所示:

 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 

应该指出的是,纯粹基于整数的方法不会考虑闰日/秒。 如果用例处理的是真实date/时间,则应使用date和日历 。

SWIFT 3.0解决scheme大致基于上述使用扩展的解决scheme。

 extension CMTime { var durationText:String { let totalSeconds = CMTimeGetSeconds(self) let hours:Int = Int(totalSeconds.truncatingRemainder(dividingBy: 86400) / 3600) let minutes:Int = Int(totalSeconds.truncatingRemainder(dividingBy: 3600) / 60) let seconds:Int = Int(totalSeconds.truncatingRemainder(dividingBy: 60)) if hours > 0 { return String(format: "%i:%02i:%02i", hours, minutes, seconds) } else { return String(format: "%02i:%02i", minutes, seconds) } } } 

用它与AVPlayer这样调用它?

  let dTotalSeconds = self.player.currentTime() playingCurrentTime = dTotalSeconds.durationText 

这是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 } 

最简单的方法是:

 let hours = time / 3600 let minutes = (time / 60) % 60 let seconds = time % 60 return String(format: "%0.2d:%0.2d:%0.2d", hours, minutes, seconds) 

根据GoZoner的回答,我写了一个扩展来获取按照小时,分钟和秒钟格式化的时间:

 extension Double { func secondsToHoursMinutesSeconds () -> (Int?, Int?, Int?) { let hrs = self / 3600 let mins = (self.truncatingRemainder(dividingBy: 3600)) / 60 let seconds = (self.truncatingRemainder(dividingBy:3600)).truncatingRemainder(dividingBy:60) return (Int(hrs) > 0 ? Int(hrs) : nil , Int(mins) > 0 ? Int(mins) : nil, Int(seconds) > 0 ? Int(seconds) : nil) } func printSecondsToHoursMinutesSeconds () -> String { let time = self.secondsToHoursMinutesSeconds() switch time { case (nil, let x? , let y?): return "\(x) min \(y) sec" case (nil, let x?, nil): return "\(x) min" case (let x?, nil, nil): return "\(x) hr" case (nil, nil, let x?): return "\(x) sec" case (let x?, nil, let z?): return "\(x) hr \(z) sec" case (let x?, let y?, nil): return "\(x) hr \(y) min" case (let x?, let y?, let z?): return "\(x) hr \(y) min \(z) sec" default: return "n/a" } } } let tmp = 3213123.printSecondsToHoursMinutesSeconds() // "892 hr 32 min 3 sec" 

NSTimeIntervalDouble做扩展。 例:

 extension Double { var formattedTime: String { var formattedTime = "0:00" if self > 0 { let hours = Int(self / 3600) let minutes = Int(truncatingRemainder(dividingBy: 3600) / 60) formattedTime = String(hours) + ":" + (minutes < 10 ? "0" + String(minutes) : String(minutes)) } return formattedTime } } 

我继续为此创build了一个闭包(在Swift 3中)。

 let (m, s) = { (secs: Int) -> (Int, Int) in return ((secs % 3600) / 60, (secs % 3600) % 60) }(299) 

这将给m = 4和s = 59.所以你可以格式化,如你所愿。 如果没有更多的信息,你当然也可以增加小时数。