Convert Date String to Int Swift

后端 未结 3 1395
时光取名叫无心
时光取名叫无心 2021-01-19 14:39

I am trying to convert the string:

let time = \"7:30\"

to integers:

let hour : Int = 7
let minutes : Int = 30
3条回答
  •  天命终不由人
    2021-01-19 15:19

    Use String.componentsSeparatedByString to split time string to parts:

    import Foundation
    
    let time = "7:30"
    let timeParts = time.componentsSeparatedByString(":")
    
    if timeParts.count == 2 {
        if let hour = Int(timeParts[0]),
            let minute = Int(timeParts[1]) {
                // use hour and minute
        }
    }
    

    If you do not want to import Foundation you can split time string to parts with:

    let timeParts = time.characters.split(":").map(String.init)
    

提交回复
热议问题