Anilkumar iOS Developer
Anilkumar iOS Developer

Reputation: 3755

How to get time difference between two times

I am working on iOS swift application. And I am running timer for 6 minutes. In that 6 minutes user can do some task, Also I am showing cancel option too. User can cancel that task too after timer started.

In UI, I am showing timer decrement in label like 06:00, 05:59 till 00:00

So, I have to calculate how much time user has worked on that task.

So, total 6 minutes duration minus user worked time (like 10 seconds, 1 minute like that)

  let difference = testDuration(testTime: "00:10") //assume 10 seconds user taken test


func testDuration(testTime: String) -> String {
    let totalTestDuration = "06:00"
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "mm:ss"
    let totalTestTime = dateFormatter.date(from: totalTestDuration)!
    let userWalkedTime = dateFormatter.date(from: testTime)!

    let calendar = Calendar.current
    let totalComponents = calendar.dateComponents([.minute, .second], from: totalTestTime)
    let userWalkedComponents = calendar.dateComponents([.minute, .second], from: userWalkedTime)

    let difference = calendar.dateComponents([.minute], from: totalComponents, to: userWalkedComponents).minute!
    
    print("difference", difference)
    return String(difference)

}

But, Always it is getting as 0

Any suggestions?

Upvotes: 1

Views: 1483

Answers (1)

christophriepe
christophriepe

Reputation: 1673

To solve this you need to get familiar with TimeIntervals.

The probably easiest approach would be to get the timeIntervalSince1970, which is representing the amount of seconds since 01.01.1970 00:00..

After that you can simply substract: newDate.timeIntervalSince1970 - oldDate.timeIntervalSince1970

This gives you the seconds between these two dates. You can then convert the result into hours, days, etc.

let oldDate: Date = Your Old Date
let newDate: Date = Your New Date

let difference = newDate.timeIntervalSince1970 - oldDate.timeIntervalSince1970

Upvotes: 3

Related Questions