If you are working with simple time calculations (i.e., adding a couple of hours to a specific time), you can do this:
let startTime = //get your start time however you want
let endTime = startTime.addingTimeInterval(numberOfHoursToAdd * 60)
But if you want to be entirely correct and account for things like daylight saving time, timespans that cross day or month boundaries, etc, you should do something more like this:
let startTime = //get your start time however you want
let endTime = Calendar.current.date(byAdding: .hour, value: numberOfHoursToAdd, to: startTime)
You can wrap that up in a convenient extension on Date
to make it cleaner at the call site:
extension Date {
func adding(minutes: Int) -> Date {
Calendar.current.date(byAdding: .minute, value: minutes, to: self)!
}
func adding(hours: Int) -> Date {
Calendar.current.date(byAdding: .hour, value: hours, to: self)!
}
}
let startTime = Date.now
let endTime = startTime.adding(hours: 3)
print(startTime)
print(endTime)