ios Swift - 整数转换为小时/分钟/秒
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/26794703/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Swift - Integer conversion to Hours/Minutes/Seconds
提问by Joe
I have a (somewhat?) basic question regarding time conversions in Swift.
我有一个(有点?)关于Swift时间转换的基本问题。
I have an integer that I would like converted into Hours / Minutes / Seconds.
我有一个整数,我想将其转换为小时/分钟/秒。
Example:Int = 27005
would give me:
示例:Int = 27005
会给我:
7 Hours 30 Minutes 5 Seconds
I know how to do this in PHP, but alas, swift isn't PHP :-)
我知道如何在 PHP 中执行此操作,但是 swift 不是 PHP :-)
Any tips on how I can achieve this in swift would be fantastic! Thank you in advance!
关于如何快速实现这一目标的任何提示都会很棒!先感谢您!
回答by GoZoner
Define
定义
func secondsToHoursMinutesSeconds (seconds : Int) -> (Int, Int, Int) {
return (seconds / 3600, (seconds % 3600) / 60, (seconds % 3600) % 60)
}
Use
用
> secondsToHoursMinutesSeconds(27005)
(7,30,5)
or
或者
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 or can access individual tuple members, if need be.
上面的函数使用 Swift 元组一次返回三个值。let (var, ...)
如果需要,您可以使用语法解构元组,或者可以访问单个元组成员。
If you actually need to print it out with the words Hours
etc then use something like this:
如果您确实需要Hours
使用单词等将其打印出来,请使用以下内容:
func printSecondsToHoursMinutesSeconds (seconds:Int) -> () {
let (h, m, s) = secondsToHoursMinutesSeconds (seconds)
print ("\(h) Hours, \(m) Minutes, \(s) Seconds")
}
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:
请注意,上述实现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)
}
回答by vadian
In macOS 10.10+ / iOS 8.0+ (NS)DateComponentsFormatter
has been introduced to create a readable string.
在 macOS 10.10+ / iOS 8.0+(NS)DateComponentsFormatter
中引入了创建可读字符串。
It considers the user's locale und language.
它考虑用户的语言环境和语言。
let interval = 27005
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute, .second]
formatter.unitsStyle = .full
let formattedString = formatter.string(from: TimeInterval(interval))!
print(formattedString)
The available unit styles are positional
, abbreviated
, short
, full
, spellOut
and brief
.
可用的单元样式positional
,abbreviated
,short
,full
,spellOut
和brief
。
For more information please read the documenation.
有关更多信息,请阅读文档。
回答by Adrian
Building upon Vadian's answer, I wrote an extension that takes a Double
(of which TimeInterval
is a type alias) and spits out a string formatted as time.
基于Vadian 的回答,我编写了一个扩展,它接受一个Double
(其中TimeInterval
是一个类型别名)并吐出一个格式化为时间的字符串。
extension Double {
func asString(style: DateComponentsFormatter.UnitsStyle) -> String {
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute, .second, .nanosecond]
formatter.unitsStyle = style
guard let formattedString = formatter.string(from: self) else { return "" }
return formattedString
}
}
Here are what the various DateComponentsFormatter.UnitsStyle
options look like:
以下是各种DateComponentsFormatter.UnitsStyle
选项的外观:
10000.asString(style: .positional) // 2:46:40
10000.asString(style: .abbreviated) // 2h 46m 40s
10000.asString(style: .short) // 2 hr, 46 min, 40 sec
10000.asString(style: .full) // 2 hours, 46 minutes, 40 seconds
10000.asString(style: .spellOut) // two hours, forty-six minutes, forty seconds
10000.asString(style: .brief) // 2hr 46min 40sec
回答by David Seek
I have built a mashup of existing answers to simplify everything and reduce the amount of code needed for Swift 3.
我已经构建了一个现有答案的混搭,以简化一切并减少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)"
}
Usage:
用法:
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)")
}
Prints:
印刷:
00:01:40
00:01:40
回答by NoLongerContributingToSE
Here is a more structured/flexible approach: (Swift 3)
这是一种更加结构化/灵活的方法:(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 Dateand Calendarshould be used.
回答by DialDT
In Swift 5:
在 Swift 5 中:
var i = 9897
func timeString(time: TimeInterval) -> String {
let hour = Int(time) / 3600
let minute = Int(time) / 60 % 60
let second = Int(time) % 60
// return formated string
return String(format: "%02i:%02i:%02i", hour, minute, second)
}
To call function
调用函数
timeString(time: TimeInterval(i))
Will return 02:44:57
将返回02:44:57
回答by r3dm4n
Swift 4
斯威夫特 4
func formatSecondsToString(_ seconds: TimeInterval) -> String {
if seconds.isNaN {
return "00:00"
}
let Min = Int(seconds / 60)
let Sec = Int(seconds.truncatingRemainder(dividingBy: 60))
return String(format: "%02d:%02d", Min, Sec)
}
回答by neeks
Here is another simple implementation in Swift3.
这是 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
}
回答by user3069232
SWIFT 3.0 solution based roughly on the one above using extensions.
SWIFT 3.0 解决方案大致基于上述使用扩展的解决方案。
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)
}
}
}
Use it with AVPlayer calling it like this?
使用它与 AVPlayer 调用它吗?
let dTotalSeconds = self.player.currentTime()
playingCurrentTime = dTotalSeconds.durationText
回答by Roman Podymov
I had answered to the similar question, however you don't need to display milliseconds in the result. Hence my solution requires iOS 10.0, tvOS 10.0, watchOS 3.0 or macOS 10.12.
我已经回答了类似的问题,但是您不需要在结果中显示毫秒。因此,我的解决方案需要 iOS 10.0、tvOS 10.0、watchOS 3.0 或 macOS 10.12。
You should call func convertDurationUnitValueToOtherUnits(durationValue:durationUnit:smallestUnitDuration:)
from the answer that I already mentioned here:
您应该func convertDurationUnitValueToOtherUnits(durationValue:durationUnit:smallestUnitDuration:)
从我在这里提到的答案中拨打电话:
let secondsToConvert = 27005
let result: [Int] = convertDurationUnitValueToOtherUnits(
durationValue: Double(secondsToConvert),
durationUnit: .seconds,
smallestUnitDuration: .seconds
)
print("\(result[0]) hours, \(result[1]) minutes, \(result[2]) seconds") // 7 hours, 30 minutes, 5 seconds