将 String 分秒转换为 Int

Convert String minutes seconds to Int

我有一个包含分钟和秒的字符串,格式为 "minutes:seconds"。例如,“5:36”。我想将它转换为 Int 值。例如“5:36”字符串应该是 336 Int 值。如何做到这一点?

我在操场上试过你的例子,代码如下:

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)
}
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)

这里有一个简单的扩展,您可以使用它来验证输入字符串的格式:

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)"