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.
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)!)
I tried to use your code and it worked great for the hours did not get the minutes all right. Espasially when it goes from one day to another. I have figured out a code that just takes to times and figures out the hours and minutes. So if anyone else is struggling with this here´s my code:
let time1 = "11.30"
let time2 = "13.40"
let formatter = DateFormatter()
formatter.dateFormat = "HH:mm"
let date1 = formatter.date(from: time1)!
let date2 = formatter.date(from: time2)!
let elapsedTime = date2.timeIntervalSince(date1)
let hours = floor(elapsedTime / 60 / 60)
let minutes = floor((elapsedTime - (hours * 60 * 60)) / 60)
var hoursfix: Int?
if Int(hours) < 0 {
hoursfix = 24 + Int(hours)
} else {
hoursfix = Int(hours)
}
print("\(hoursfix ?? 0) hr and \(Int(minutes)) min")