将字符串的分钟数秒转换为整数
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了将字符串的分钟数秒转换为整数相关的知识,希望对你有一定的参考价值。
我有一个带有分钟和秒的字符串,格式为“分钟:秒”。例如,“ 5:36”。我想将其转换为Int值。例如,“ 5:36”字符串应为336 Int值。如何做到这一点?
答案
这是您可以使用的简单扩展名,它也将验证您输入字符串的格式:
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)"
另一答案
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
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)
以上是关于将字符串的分钟数秒转换为整数的主要内容,如果未能解决你的问题,请参考以下文章