How to add minutes to current time in swift
You can use Calendar's method
func date(byAdding component: Calendar.Component, value: Int, to date: Date, wrappingComponents: Bool = default) -> Date?
to add any Calendar.Component
to any Date
. You can create a Date extension to add x minutes to your UIDatePicker
's date:
Xcode 8 and Xcode 9 • Swift 3.0 and Swift 4.0
extension Date {
func adding(minutes: Int) -> Date {
return Calendar.current.date(byAdding: .minute, value: minutes, to: self)!
}
}
Then you can just use the extension method to add minutes to the sender (UIDatePicker):
let section1 = sender.date.adding(minutes: 5)
let section2 = sender.date.adding(minutes: 10)
Playground testing:
Date().adding(minutes: 10) // "Jun 14, 2016, 5:31 PM"
Two approaches:
Use
Calendar
anddate(byAdding:to:wrappingComponents:)
. E.g., in Swift 3 and later:let calendar = Calendar.current let date = calendar.date(byAdding: .minute, value: 5, to: startDate)
Just use
+
operator (see+(_:_:)
) to add aTimeInterval
(i.e. a certain number of seconds). E.g. to add five minutes, you can:let date = startDate + 5 * 60
(Note, the order is specific here: The date on the left side of the
+
and the seconds on the right side.)You can also use
addingTimeInterval
, if you’d prefer:let date = startDate.addingTimeInterval(5 * 60)
Bottom line, +
/addingTimeInterval
is easiest for simple scenarios, but if you ever want to add larger units (e.g., days, months, etc.), you would likely want to use the calendrical calculations because those adjust for daylight savings, whereas addingTimeInterval
doesn’t.
For Swift 2 renditions, see the previous revision of this answer.