【问题标题】:Convert String minutes seconds to Int将 String 分秒转换为 Int
【发布时间】:2020-05-16 09:51:15
【问题描述】:

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

【问题讨论】:

  • Int(m) * 60 + Int(s)
  • 下一次,先尝试自己解决并发布您的尝试。

标签: ios swift string int


【解决方案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)

【讨论】:

  • 方法不对,要先转换成日期格式
  • 不@PrashantTukadiya,这是正确的方法。 OP 没有说字符串是时钟时间值,只是它是“分钟:秒”。它可能是一个带有“2000:30”的计时器。在这种情况下,无法转换为 DateFormat。
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

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

    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 time2String = "99:36",因为它假定字符串是时钟时间。但不一定是这样。如果它是一个计数秒和分钟的计时器怎么办?如果您只是将字符串拆分并转换为整数,那么从字符串到日期的两次转换也是低效且不必要的。
    • 这对字符串 "5:36" 也不起作用,这是 OP 的原始请求。为此,格式必须为"05:36"
    • 编辑使其适用于“5:36”。 “99:36”对我来说没有意义。 “59:59”之后不应该是“1:00:00”吗?
    • 当然,取决于要求
    猜你喜欢
    • 2023-04-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-03-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多