Date calculations

by @ralfebert · published October 10, 2021
Xcode 13 & iOS 15
Swift Examples

Adding second values

Adding a number of seconds to a Date value, for example to add 5 minutes:

Date.now.addingTimeInterval(5 * 60)
Date.now + (5 * 60)

This should be only used for short durations; it might not do what you expect for example when adding day intervals with leap days in between; also the computation of the seconds is pretty unreadable and should be avoided.

Via Calendar

The Calendar class has an API to perform date calculations:

Calendar.current.date(byAdding: .minute, value: 5, to: Date.now)

Convenience extension

It might be handy to define an extension that allows to perform date calculations directly on date values:

Date.now.adding(minutes: 5)

→ Swift Package: DateCalculations
→ Date+AddingComponent.swift