将 0 添加到 hours/minutes 小于 10

add 0 to hours/minutes under 10

我有一些问题要在 swift3 中找到合适的解决方案来做到这一点:

我的约会时间是 10 点 20 分。当我的工作时间低于 10 时,它将是“5h30”。我想输出“05h30”。

class func getTime(_ user: SUser) -> String {
    let currentDate = Date()
    let firstDate = user.firstDate
    let difference = firstDate?.timeIntervalSince(now)

    let hours = String(Int(difference!) / 3600)
    let minutes = String(Int(difference!) / 60 % 60)

    let time = "\(hours)h\(minutes)m"
    return time
}

如果有人知道如何简单而正确地做到这一点,谢谢!

class func getTime(_ user: SUser) -> String {
    let currentDate = Date()
    let firstDate = user.firstDate
    let difference = firstDate?.timeIntervalSince(now)

    var hours = String(Int(difference!) / 3600)
    if ((Int(difference!) / 3600)<10) {
       hours = "0\(hours)"
    }
    var minutes = String(Int(difference!) / 60 % 60)
    if ((Int(difference!) / 60 % 60)<10) {
       minutes =  "0\(minutes)"
    }
    let time = "\(hours)h\(minutes)m"
    return time
}

你可以这样做

class func getTime(_ user: SUser) -> String {
    let currentDate = Date()
    let firstDate = user.firstDate
    let difference = firstDate?.timeIntervalSince(now)

    let hours = String(Int(difference!) / 3600)
    if Int(hours)! < 10 {
        hours = "0\(hours)"
    }
    var minutes = String(Int(difference!) / 60 % 60)
    if Int(minutes)! < 10 {
        minutes = "0\(minutes)"
    }
    let time = "\(hours)h\(minutes)m"
    return time
}

或更好的方法

class func getTime(_ user: SUser) -> String {
    let currentDate = Date()
    let firstDate = user.firstDate
    let difference = firstDate?.timeIntervalSince(now)

    let hours = Int(difference!) / 3600
    let minutes = Int(difference!) / 60 % 60

    let time = "\(String(format: "%02d", hours))h\(String(format: "%02d", minutes))m"
    return time
}

此处建议 - Leading zeros for Int in Swift

我认为您最好使用可以调用内联的简单格式化函数。

试试

func formatHour(hour:Int) -> String {

    return (String(hour).characters.count == 1) ? "0\(hour)" : "\(hour)"
}

let hour = 5

print("\(formatHour(hour: hour))") // output "05"

您可以根据需要进行调整,也许改为传入字符串并保存在函数中进行转换。还可以添加一个 guard 语句以确保数字在小时范围内,或者字符串少于三个字符等。