将字符串的分钟数秒转换为整数

问题描述 投票:0回答:3

我有一个带有分钟和秒的字符串,格式为“分钟:秒”。例如,“ 5:36”。我想将其转换为Int值。例如,“ 5:36”字符串应为336 Int值。如何做到这一点?

ios swift string int
3个回答
1
投票

这是您可以使用的简单扩展名,它也将验证您输入字符串的格式:

import Foundation

extension String {

    func toSeconds() -> Int? {

        let elements = components(separatedBy: ":")

        guard elements.count == 2 else {
            print("Provided string doesn't have two sides separated by a ':'")
            return nil
        }

        guard let minutes = Int(elements[0]),
        let seconds = Int(elements[1]) else {
           print("Either the minute value or the seconds value cannot be converted to an Int")
            return nil
        }

        return (minutes*60) + seconds

    }

}

用法:

let testString1 = "5:36"
let testString2 = "35:36"

print(testString1.toSeconds()) // prints: "Optional(336)"
print(testString2.toSeconds()) // prints: "Optional(2136)"

1
投票
let timeString = "5:36"
let timeStringArray = timeString.split(separator: ":")
let minutesInt = Int(timeStringArray[0]) ?? 0
let secondsInt = Int(timeStringArray[1]) ?? 0
let resultInt = minutesInt * 60 + secondsInt
print(resultInt)

1
投票

我在操场上尝试了您的示例,代码如下:

import Foundation

let time1String = "0:00"
let time2String = "5:36"

let timeformatter        = DateFormatter()
timeformatter.dateFormat = "m:ss"

let time1 = timeformatter.date(from: time1String)
let time2 = timeformatter.date(from: time2String)

if let time1 = time1 {
    print(time2?.timeIntervalSince(time1)) // prints: Optional(336.0)
}
© www.soinside.com 2019 - 2024. All rights reserved.