Calculate time from start and stop times

Hi!

I am building an app including start and stop time. I have gathered the start and stop time. I want the code then to calculate how many hours and minutes it lasted for. e.g Start time: 16:00, End time: 20:00 (Yes I use 24hour clock), then I want the code to calculate that this is 4 hours and print it.

Thanks

Hi Vegard,

This was a fun puzzle to figure out! :slight_smile:

You can try this, it will provide the hour difference

var time1 = Date()
var time2 = Date()

func setHour( _ time:Int ) -> Date {
   
    let gregorian = NSCalendar(calendarIdentifier: NSCalendar.Identifier.gregorian)!
    let now = NSDate()
    var components = gregorian.components([.hour], from: now as Date)

    components.hour = time
   
     return gregorian.date(from: components)!
}

time2 = setHour(16)
time1 = setHour(20)

let formatter = DateComponentsFormatter()
formatter.allowedUnits = [.hour, .minute]
print(formatter.string(from: time2, to: time1)!)

Blessings,
—Mark

Thanks a lot. I will try this in my project. An I will Come back to tel. You if it worked how I wanted it