计算Swift中Int的时差

时间:2017-10-19 14:54:31

标签: swift time int

我需要计算两个Int之间的差异并将其格式化以显示小时,分钟。我可以将下面的函数部分地与初始的int差异区分开来。

示例:如果我有0811的起始Int,然后是0912的结束Int,则差异为101.如果我从结果中取12,我应该91 1}}。当我使用结果转换为时间时,它返回1小时31分钟 - 这是正确的。但是我需要以某种方式将它进一步转换为链,然后将其关闭以正确格式化时间。这应该意味着101应该是1小时1分钟。

func calculateTimeDifference(start: Int, end: Int, longVersion: Bool) -> String {

    let count = end - start
    let total = minutesToHoursMinutes(minutes: count)
    var formatted = ""

    if total.hours != 0 {
        formatted += "\(total.hours)"
        let amount = total.hours > 1 ? " hours " : " hour "
        formatted += amount
    }

    if total.leftMinutes != 0 {
        formatted += "\(total.leftMinutes)"
        let amount = total.leftMinutes > 1 ? " minutes " : " minute "
        formatted += amount
    }

    return String(describing: formatted)

}

func minutesToHoursMinutes(minutes : Int) -> (hours : Int, leftMinutes : Int) {
    return (minutes / 60, (minutes % 60))
}

3 个答案:

答案 0 :(得分:2)

你不应该通过减去它来计算Date s中表达的两次之间的差异。使用正确的Int API。

在这里,我首先将timeIntervalSince转换为字符串,然后使用日期格式化程序对它们进行解析。之后func calculateTimeDifference(start: Int, end: Int) -> String { let formatter = DateFormatter() formatter.dateFormat = "HHmm" var startString = "\(start)" if startString.characters.count < 4 { for _ in 0..<(4 - startString.characters.count) { startString = "0" + startString } } var endString = "\(end)" if endString.characters.count < 4 { for _ in 0..<(4 - endString.characters.count) { endString = "0" + endString } } let startDate = formatter.date(from: startString)! let endDate = formatter.date(from: endString)! let difference = endDate.timeIntervalSince(startDate) return "\(Int(difference) / 3600)Hr \(Int(difference) % 3600 / 60)Min" } 可以告诉你几秒钟的差异。你需要一些模数和除法来得到小时和分钟:

{{1}}

答案 1 :(得分:1)

继承你正在从一个奇怪的角度接近这个并导致自己的问题。

而不是不适合存储时间的Int,使用可以保存完整日期信息的TimeInterval,例如:

let second:TimeInterval = 1.0
let minute:TimeInterval = 60.0
let hour:TimeInterval = 60.0 * minute
let day:TimeInterval = 24 * hour 

然后,当你想确定两次之间的时差时,这是非常基本的算法。

Playground example

答案 2 :(得分:0)

SWIFT 4

在Swift 4中characters已被弃用,因此Swift 4中的Sweepers解决方案

func calculateTimeDifference(start: Int, end: Int) -> String {
    let formatter = DateFormatter()
    formatter.dateFormat = "HHmm"
    var startString = "\(start)"
    if startString.count < 4 {
        for _ in 0..<(4 - startString.count) {
            startString = "0" + startString
        }
    }
    var endString = "\(end)"
    if endString.count < 4 {
        for _ in 0..<(4 - endString.count) {
            endString = "0" + endString
        }
    }
    let startDate = formatter.date(from: startString)!
    let endDate = formatter.date(from: endString)!
    let difference = endDate.timeIntervalSince(startDate)
    return "\(Int(difference) / 3600)Hr \(Int(difference) % 3600 / 60)Min"
}