Search code examples
iosswiftdatetimedateformatter

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.


Solution

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