I have to obtain the sum of two times. Now I have the two times in arrays (24h format not am/pm).
This is the code I wrote:
let time1 = "03:4"
let time2 = "4:02"
let firstTime = formatter.date(from: time1)!
let secondTime = formatter.date(from: time2)!
var Total = firstTime.addingTimeInterval(secondTime)
text1.StringValue = (Total)
But I receive this error: Cannot convert value of type 'Date' to expected argument type 'TimeInterval' (aka 'Double')
You might want to make some "reference point" before adding. Since you're adding "duration" instead of "time". That could make the calculation simpler since Date and TimeInterval has a lot of "intuitive" arithmetic.
The problem is that each Date contains both day and time. It makes little sense to add two Dates together. That's also why you need to resort to all these date <~> hour/minute conversion shenanigans when all you wanted to do is just
I may go against the tide, but for this specific use case I would prefer a custom type. You're not really working with dates, you're working with durations more akin to video durations. The only similarity is the "HH:mm" format used to represent them. There's also a chance to get something wrong by not considering time zones when using a date formatter. Even more, although it's not possible to exceed 24 hours by mean of adding two working times of the same day, if you need to, e.g., compute the average of work time per day during a week, date formatters wouldn't be of much help. Lastly, you're working with whole minutes, so that's better handled by Ints than Doubles.
struct WorkTime {
let minutes: Int
init(minutes: Int) { self.minutes = minutes }
init?(_ string: String) {
let elements = string.split(separator: ":").map { Int($0) }
guard let hh = elements[0], let mm = elements[1] else { return nil }
minutes = hh * 60 + mm
}
static func + (lhs: WorkTime, rhs: WorkTime) -> WorkTime {
.init(minutes: lhs.minutes + rhs.minutes)
}
var description: String {
let (hh, mm) = minutes.quotientAndRemainder(dividingBy: 60)
return "\(hh):\(mm)"
}
}
Then you can sum them using:
if let time1 = WorkTime("3:18"), let time2 = WorkTime("5:15") {
let total = time1 + time2
print(total.description)
}
I found by chance a framework on github that was right for me (in practice it allowed to perform the various calculations on the dates in a rather simple way) and thanks to this I managed to complete the program. Surely, however, the solution proposed by XAlien95 is much more immediate and faster, I have written many more lines of code to obtain the same result ....