John Martin
John Martin

Reputation: 453

Time Duration From Labels

I've looked at all the Code on here that has to do with getting time duration. All I need to do is simply take a time that is in a label in this format hr:m:s like 20:23:04 for example. I need to take the times from currentTime.StringValue and the time from oldTime.StringValue and then have it show the duration of hours in durationOfTime.StringValue.

So for example say currentTime = 11:00:04 and oldTime = 9:00:04 then I want durationOfTime = 2hr's.

That's it right now I have a code that get's the time and stores it in the format above. However I run into all kinds of problems trying different codes on here that have to do with Time Duration.

Upvotes: 3

Views: 223

Answers (2)

Anters Bear
Anters Bear

Reputation: 1956

Hope this is helpful. Edited maddy's suggestion.

    let currentTime = "11:00:04"
    let oldTime = "9:00:04"

    let currentTimeComponents = currentTime.components(separatedBy: ":")
    let oldTimeComponents = oldTime.components(separatedBy: ":")

    let hrsDifference = Int(currentTimeComponents[0])! - Int(oldTimeComponents[0])!
    let minutesDifference = Int(currentTimeComponents[1])! - Int(oldTimeComponents[1])!
    let secondsDifference = Int(currentTimeComponents[2])! - Int(oldTimeComponents[2])!

    print("hrsDifference = ",hrsDifference)
    print("minutesDifference = ",minutesDifference)
    print("secondsDifference = ",secondsDifference)

Upvotes: 0

Code Different
Code Different

Reputation: 93161

Use 2 formatters: a DateFormatter to convert the strings to Date objects and a DateComponentFormatter to display the duration between the 2 Dates:

let currentTimeStr = "11:00:04"
let oldTimeStr = "9:00:04"

let dateFormatter = DateFormatter()
dateFormatter.dateFormat = "H:mm:ss"

let dateComponentFormatter = DateComponentsFormatter()
dateComponentFormatter.allowedUnits = [.hour, .minute]
dateComponentFormatter.unitsStyle = .short

if let currentTime = dateFormatter.date(from: currentTimeStr),
    let oldTime = dateFormatter.date(from: oldTimeStr),
    let durationStr = dateComponentFormatter.string(from: oldTime, to: currentTime)
{
    print(durationStr) // 2 hrs
}

Upvotes: 2

Related Questions