ios 快速从 NSTimeInterval 转换为小时、分钟、秒、毫秒
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/28872450/
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
conversion from NSTimeInterval to hour,minutes,seconds,milliseconds in swift
提问by Lydia
My code is here:
我的代码在这里:
func stringFromTimeInterval(interval:NSTimeInterval) -> NSString {
var ti = NSInteger(interval)
var ms = ti * 1000
var seconds = ti % 60
var minutes = (ti / 60) % 60
var hours = (ti / 3600)
return NSString(format: "%0.2d:%0.2d:%0.2d",hours,minutes,seconds,ms)
}
in output the milliseconds give wrong result.Please give an idea how to find milliseconds correctly.
在输出中毫秒给出错误的结果。请给出如何正确找到毫秒的想法。
回答by Matthias Bauch
Swift supports remainder calculations on floating-point numbers, so we can use % 1
.
Swift 支持浮点数的余数计算,因此我们可以使用% 1
.
var ms = Int((interval % 1) * 1000)
as in:
如:
func stringFromTimeInterval(interval: TimeInterval) -> NSString {
let ti = NSInteger(interval)
let ms = Int((interval % 1) * 1000)
let seconds = ti % 60
let minutes = (ti / 60) % 60
let hours = (ti / 3600)
return NSString(format: "%0.2d:%0.2d:%0.2d.%0.3d",hours,minutes,seconds,ms)
}
result:
结果:
stringFromTimeInterval(12345.67) "03:25:45.670"
Swift 4:
斯威夫特 4:
extension TimeInterval{
func stringFromTimeInterval() -> String {
let time = NSInteger(self)
let ms = Int((self.truncatingRemainder(dividingBy: 1)) * 1000)
let seconds = time % 60
let minutes = (time / 60) % 60
let hours = (time / 3600)
return String(format: "%0.2d:%0.2d:%0.2d.%0.3d",hours,minutes,seconds,ms)
}
}
Use:
用:
self.timeLabel.text = player.duration.stringFromTimeInterval()
回答by Jake Cronin
SWIFT 3 Extension
SWIFT 3 扩展
I think this way is a easier to see where each piece comes from so you can more easily modify it to your needs
我认为这种方式更容易查看每个部分的来源,因此您可以更轻松地根据需要对其进行修改
extension TimeInterval {
private var milliseconds: Int {
return Int((truncatingRemainder(dividingBy: 1)) * 1000)
}
private var seconds: Int {
return Int(self) % 60
}
private var minutes: Int {
return (Int(self) / 60 ) % 60
}
private var hours: Int {
return Int(self) / 3600
}
var stringTime: String {
if hours != 0 {
return "\(hours)h \(minutes)m \(seconds)s"
} else if minutes != 0 {
return "\(minutes)m \(seconds)s"
} else if milliseconds != 0 {
return "\(seconds)s \(milliseconds)ms"
} else {
return "\(seconds)s"
}
}
}
回答by Minos
Equivalent in Objective-C, based on the @matthias-bauch answer.
等效于 Objective-C,基于@matthias-bauch 的答案。
+ (NSString *)stringFromTimeInterval:(NSTimeInterval)timeInterval
{
NSInteger interval = timeInterval;
NSInteger ms = (fmod(timeInterval, 1) * 1000);
long seconds = interval % 60;
long minutes = (interval / 60) % 60;
long hours = (interval / 3600);
return [NSString stringWithFormat:@"%0.2ld:%0.2ld:%0.2ld,%0.3ld", hours, minutes, seconds, (long)ms];
}
回答by vadian
Swift 3 solution for iOS 8+, macOS 10.10+ if the zero-padding of the hours doesn't matter:
如果小时的零填充无关紧要,则适用于 iOS 8+、macOS 10.10+ 的 Swift 3 解决方案:
func stringFromTime(interval: TimeInterval) -> String {
let ms = Int(interval.truncatingRemainder(dividingBy: 1) * 1000)
let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute, .second]
return formatter.string(from: interval)! + ".\(ms)"
}
print(stringFromTime(interval: 12345.67)) // "3:25:45.670"
回答by Mohammad Razipour
Swift 4:
斯威夫特 4:
extension TimeInterval{
func stringFromTimeInterval() -> String {
let time = NSInteger(self)
let ms = Int((self.truncatingRemainder(dividingBy: 1)) * 1000)
let seconds = time % 60
let minutes = (time / 60) % 60
let hours = (time / 3600)
return String(format: "%0.2d:%0.2d:%0.2d.%0.3d",hours,minutes,seconds,ms)
}
}
Use:
用:
self.timeLabel.text = player.duration.stringFromTimeInterval()
回答by mirap
Swift 4, without using the .remainder
(which returns wrong values):
Swift 4,不使用.remainder
(返回错误值):
func stringFromTimeInterval(interval: Double) -> NSString {
let hours = (Int(interval) / 3600)
let minutes = Int(interval / 60) - Int(hours * 60)
let seconds = Int(interval) - (Int(interval / 60) * 60)
return NSString(format: "%0.2d:%0.2d:%0.2d",hours,minutes,seconds)
}
回答by lilpit
I think most of those answers are outdated, you should always use DateComponentsFormatter if you want to display a string representing a time interval, because it will handle padding and localization for you.
我认为这些答案中的大多数已经过时,如果您想显示表示时间间隔的字符串,您应该始终使用 DateComponentsFormatter,因为它会为您处理填充和本地化。
回答by maslovsa
Swift 4 (with Range check ~ without Crashes)
Swift 4(带范围检查~无崩溃)
import Foundation
extension TimeInterval {
var stringValue: String {
guard self > 0 && self < Double.infinity else {
return "unknown"
}
let time = NSInteger(self)
let ms = Int((self.truncatingRemainder(dividingBy: 1)) * 1000)
let seconds = time % 60
let minutes = (time / 60) % 60
let hours = (time / 3600)
return String(format: "%0.2d:%0.2d:%0.2d.%0.3d", hours, minutes, seconds, ms)
}
}
回答by Ohad Cohen
swift 3 version of @hixField answer, now with days and handling previous dates:
swift 3 版本的@hixField 答案,现在有天数和处理以前的日期:
extension TimeInterval {
func timeIntervalAsString(_ format : String = "dd days, hh hours, mm minutes, ss seconds, sss ms") -> String {
var asInt = NSInteger(self)
let ago = (asInt < 0)
if (ago) {
asInt = -asInt
}
let ms = Int(self.truncatingRemainder(dividingBy: 1) * (ago ? -1000 : 1000))
let s = asInt % 60
let m = (asInt / 60) % 60
let h = ((asInt / 3600))%24
let d = (asInt / 86400)
var value = format
value = value.replacingOccurrences(of: "hh", with: String(format: "%0.2d", h))
value = value.replacingOccurrences(of: "mm", with: String(format: "%0.2d", m))
value = value.replacingOccurrences(of: "sss", with: String(format: "%0.3d", ms))
value = value.replacingOccurrences(of: "ss", with: String(format: "%0.2d", s))
value = value.replacingOccurrences(of: "dd", with: String(format: "%d", d))
if (ago) {
value += " ago"
}
return value
}
}
回答by Pablo Ruan
for convert hour and minutes to seconds in swift 2.0:
在 swift 2.0 中将小时和分钟转换为秒:
///RETORNA TOTAL DE SEGUNDOS DE HORA:MINUTOS
func horasMinutosToSeconds (HoraMinutos:String) -> Int {
let formatar = NSDateFormatter()
let calendar = NSCalendar.currentCalendar()
formatar.locale = NSLocale.currentLocale()
formatar.dateFormat = "HH:mm"
let Inicio = formatar.dateFromString(HoraMinutos)
let comp = calendar.components([NSCalendarUnit.Hour, NSCalendarUnit.Minute], fromDate: Inicio!)
let hora = comp.hour
let minute = comp.minute
let hours = hora*3600
let minuts = minute*60
let totseconds = hours+minuts
return totseconds
}