在10下加0到小时/分钟

时间:2016-11-09 17:23:50

标签: ios swift nsdate swift3

我在swift3中找到一个合适的解决方案来解决这个问题:

我有一个像10h20m的日期。当我的小时数低于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
}

如果有人知道怎么做,那么简单地感谢你!

3 个答案:

答案 0 :(得分:1)

你可以做这样的事情

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

答案 1 :(得分:0)

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
}

答案 2 :(得分:0)

我认为你可以使用一个简单的格式化功能,你可以内联调用。

尝试类似

的内容
public static String audienceFormat(int number) {
    String value = String.valueOf(number);

    if (value.length() > 6) {
            value = value.replaceFirst("(\\d{1,3})(\\d{3})(\\d{3})", "$1\u00B4$2,$3");
        } else if (value.length() >=5 && value.length() <= 6) {
            value = value.replaceFirst("(\\d{2,3})(\\d{3})", "$1,$2");
        }  else {
            value = value.replaceFirst("(\\d{1})(\\d+)", "$1,$2");
        }

    return value;
} 

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