如何在Swift中解析ISO 8601持续时间格式? [英] How to parse a ISO 8601 duration format in Swift?

查看:89
本文介绍了如何在Swift中解析ISO 8601持续时间格式?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个函数,可以在下面使用该函数格式化字符串.该字符串类似于"PT1H3M20S",表示1小时3分20秒.在我的函数中,我想将字符串格式化为1:03:20,并且可以正常工作,但是有时,我会得到像这样的字符串"PT1H20S",这意味着1小时20秒,而我的函数将其格式化为1:20,使人们阅读它的时间为1分20秒.有什么建议吗?

I have a function below which I use to format a string. The string is something like this "PT1H3M20S" which means 1 hour 3 minutes and 20 seconds. In my function, I want to format the string to 1:03:20 and it works fine but sometimes, I get the string like this "PT1H20S" which means 1 hour and 20 seconds and my function format it like this 1:20 which makes people read it as 1 minute and 20 seconds. Any suggestions?

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
}

调用:

print(formatDuration(videoDuration: "PT1H15S")

推荐答案

您还可以只搜索小时,分钟和秒的索引,并使用DateComponentsFormatter位置样式来设置视频时长:

You can also just search the indexes of your hours, minutes and seconds and use DateComponentsFormatter positional style to format your video duration:

创建静态位置日期成分格式化程序:

Create a static positional date components formatter:

extension Formatter {
    static let positional: DateComponentsFormatter = {
        let formatter = DateComponentsFormatter()
        formatter.unitsStyle = .positional
        return formatter
    }()
}

以及格式持续时间方法:

And your format duration method:

func formatVideo(duration: String) -> String {
    var duration = duration
    if duration.hasPrefix("PT") { duration.removeFirst(2) }
    let hour, minute, second: Double
    if let index = duration.index(of: "H") {
        hour = Double(duration[..<index]) ?? 0
        duration.removeSubrange(...index)
    } else { hour = 0 }
    if let index = duration.index(of: "M") {
        minute = Double(duration[..<index]) ?? 0
        duration.removeSubrange(...index)
    } else { minute = 0 }
    if let index = duration.index(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"

这篇关于如何在Swift中解析ISO 8601持续时间格式?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆