如何在 Swift 中将 TimeInterval 转换为分钟、秒和毫秒 [英] How to convert TimeInterval into Minutes, Seconds and Milliseconds in Swift
问题描述
我正在编写一个赛车应用程序,想将大量毫秒数转换为分钟数:seconds.milliseconds(例如,1:32.361
).目前我只是通过数学计算(minutes/60000
),然后得到余数并进一步除以等等,但我发现它时不时地关闭 1 毫秒.我知道这听起来可能没什么大不了的,但我试图找到 1:32.004
和 1:32.004
的平均值,结果返回了 1:32.003
,这意味着它被错误地放入并且应用程序的其余部分无法处理它.
I am writing a racing app and want to convert a large number of milliseconds into minutes:seconds.milliseconds (for example, 1:32.361
). At the moment I just do it through maths (minutes / 60000
), then get remainder and divide further, etc., but i find that it is off every now and then by 1 millisecond. I know this might not sound like a big deal, but I tried to find the average of 1:32.004
and 1:32.004
and it returned 1:32.003
, which means it gets put in incorrectly and the rest of the app can't deal with it.
有没有办法使用 NSDate
或 NSDateFormatter
或类似的东西将毫秒格式化为 MM:ss.mmm?
Is there a way to use NSDate
or NSDateFormatter
or something like that to format the milliseconds into MM:ss.mmm?
我查看了这些来源,但没有找到答案:
I have looked at these sources but not found the answer:
如何将毫秒转换为分钟?
将秒转换为分钟和秒
将毫秒转换为分钟
http://www.codingexplorer.com/swiftly-getting-human-可读日期nsdateformatter/
推荐答案
您可以创建一个 TimeInterval 扩展来格式化您的经过时间,如下所示:
You can create a TimeInterval extension to format your elapsed time as follow:
Xcode 11.4 • Swift 5.2 或更高版本
extension TimeInterval {
var hourMinuteSecondMS: String {
String(format:"%d:%02d:%02d.%03d", hour, minute, second, millisecond)
}
var minuteSecondMS: String {
String(format:"%d:%02d.%03d", minute, second, millisecond)
}
var hour: Int {
Int((self/3600).truncatingRemainder(dividingBy: 3600))
}
var minute: Int {
Int((self/60).truncatingRemainder(dividingBy: 60))
}
var second: Int {
Int(truncatingRemainder(dividingBy: 60))
}
var millisecond: Int {
Int((self*1000).truncatingRemainder(dividingBy: 1000))
}
}
extension Int {
var msToSeconds: Double { Double(self) / 1000 }
}
let seconds = 131.531 // 131.531
let time = seconds.minuteSecondMS // "2:11.531"
let millisecond = seconds.millisecond // 531
let ms = 1111
let sec = ms.msToSeconds.minuteSecondMS // "0:01.111"
Date().description(with: .current) // "Wednesday, October 21, 2020 at 5:44:51 PM Brasilia Standard Time"
let startOfDay = Calendar.current.startOfDay(for: Date())
let secondsFromStartOfDay = Date().timeIntervalSinceReferenceDate - startOfDay.timeIntervalSinceReferenceDate
secondsFromStartOfDay.hourMinuteSecondMS // "17:44:51.705"
这篇关于如何在 Swift 中将 TimeInterval 转换为分钟、秒和毫秒的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!