2025-01-01
Adding/Subtracting from a Date
extension Date {
/// Adds the specified time components to this date
func add(years: Int = 0, months: Int = 0, days: Int = 0, hours: Int = 0, minutes: Int = 0, seconds: Int = 0) -> Date? {
let components = DateComponents(year: years, month: months, day: days, hour: hours, minute: minutes, second: seconds)
return Calendar.current.date(byAdding: components, to: self)
}
/// Subtracts the specified components from this date
func subtract(years: Int = 0, months: Int = 0, days: Int = 0, hours: Int = 0, minutes: Int = 0, seconds: Int = 0) -> Date? {
return add(years: -years, months: -months, days: -days, hours: -hours, minutes: -minutes, seconds: -seconds)
}
}
Usage:
// Add one year and a half to the current Date:
Date().add(years: 1, months: 6)
// Add 30 seconds to the current Date:
Date().add(seconds: 30)
// Substract 10 minutes from now:
Date().add(minutes: -10)
// or
Date().sustract(minutes: 10)