我有一个函数,我用它来格式化字符串。该字符串类似于“PT1H3M20S”,表示 1 小时 3 分 20 秒。在我的函数中,我想将字符串格式化为 1:03:20 并且它工作正常,但有时,我得到像这样的字符串“PT1H20S”,这意味着 1 小时 20 秒,我的函数将其格式化为 1:20让人把它读成1分20秒。有什么建议么?
func formatDuration(videoDuration: String) -> String{
let formattedDuration = videoDuration.replacingOccurrences(of: "PT", with: "").replacingOccurrences(of: "H", with:":").replacingOccurrences(of: "M", with: ":").replacingOccurrences(of: "S", with: "")
let components = formattedDuration.components(separatedBy: ":")
var duration = ""
for component in components {
duration = duration.count > 0 ? duration + ":" : duration
if component.count < 2 {
duration += "0" + component
continue
}
duration += component
}
// instead of 01:10:10, display 1:10:10
if duration.first == "0"{
duration.remove(at: duration.startIndex)
}
return duration
}
Call it:
print(formatDuration(videoDuration: "PT1H15S")
您还可以只搜索小时、分钟和秒的索引,并使用 DateComponentsFormatter 位置样式来格式化视频持续时间:
创建静态位置日期组件格式化程序:
extension Formatter {
static let positional: DateComponentsFormatter = {
let formatter = DateComponentsFormatter()
formatter.unitsStyle = .positional
return formatter
}()
}
以及您的格式持续时间方法:
func formatVideo(duration: String) -> String {
var duration = duration
if duration.hasPrefix("PT") { duration.removeFirst(2) }
let hour, minute, second: Double
if let index = duration.firstIndex(of: "H") {
hour = Double(duration[..<index]) ?? 0
duration.removeSubrange(...index)
} else { hour = 0 }
if let index = duration.firstIndex(of: "M") {
minute = Double(duration[..<index]) ?? 0
duration.removeSubrange(...index)
} else { minute = 0 }
if let index = duration.firstIndex(of: "S") {
second = Double(duration[..<index]) ?? 0
} else { second = 0 }
return Formatter.positional.string(from: hour * 3600 + minute * 60 + second) ?? "0:00"
}
let duration = "PT1H3M20S"
formatVideo(duration: duration) // "1:03:20"
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)