Advancing Date values in Swift
Swift makes it easy to advance a Date
value by a given number of seconds. Just use the .addingTimeInterval()
method.
let date = Date.now
let sixtySecondsLater = date.addingTimeInterval(60)
let twentyMinutesLater = date.addingTimeInterval(60 * 20)
// Negative values also work just fine
let sixtySecondsAgo = date.addingTimeInterval(-60)
For a more readable, and less error-prone approach, use the Calendar
method of date(byAdding:…)
. You can easily and explicitly specify the date component you want to move forward (or backwards) by, as well as how much. There is an additional overload of the method which accepts a full DateComponents
object, which allows you to easily change multiple components in one go.
let date = Date.now
let oneHourLater = Calendar.current.date(byAdding: .hour, value: 1, to: date)
let twentyHoursLater = Calendar.current.date(byAdding: .hour, value: 20, to: date)
let components = DateComponents(hour: 3, minute: 20)
let threeHoursTwentyMinutesLater = Calendar.current.date(byAdding: components, to: date)
The .date(byAdding:…)
method has one last trick up its sleve. Say you are building a clock component where you can individually step the hours, minutes, or seconds up and down. If you would like the behavior to be such that incrementing the seconds from 55 to 5 to not make a change to the value of the minutes, you can set the wrappingComponents
paramter to true
.
let date = Date.now
let timeIsAnIllusion = Calendar.current.date(byAdding: .second, value: 60, to: date, wrappingComponents: true)
print(date == timeIsAnIllusion) // `true`