user7684436
user7684436

Reputation: 717

Calculate time difference from Int in Swift

I need to calculate the difference between two Int and format it to show hours, minutes. I can the function below to partially apart from the initial int difference.

Example: If i have a start Int of 0811 and then an end Int of 0912 the difference is 101. If I then take 12 from the result I should have 91. When I use the result to convert to time it returns 1 hour and 31 mins - which is correct. However I need to somehow convert it further up the chain and then take it off to format the time correctly. This should mean the 101 should be 1 hour 1 minute.

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

Upvotes: 0

Views: 1702

Answers (3)

Jan-Hendrik
Jan-Hendrik

Reputation: 13

SWIFT 4

In Swift 4 characters is deprecated, so Sweepers solution in Swift 4 is

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

Upvotes: 0

Sweeper
Sweeper

Reputation: 271565

You shouldn't calculate the difference between two times expressed in Ints by subtracting them. Use the proper Date API.

Here, I converted the Ints to strings first and then parsed them using a date formatter. After that timeIntervalSince can tell you the difference in seconds. You just need some modulus and division to get the hours and minutes from that:

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

Upvotes: 2

Damo
Damo

Reputation: 12890

Inherintly you are approaching this from a strange angle and causing yourself issues.

Instead of Int, which is inappropriate for storing a time, use TimeInterval which can hold a full date information, e.g.:

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

Then when you want to determine the time difference between two times it's very basic arithmetic.

Playground example

Upvotes: 1

Related Questions