I am new to Swift and am trying a scheduler. I have the start time selected and I need to add 5 minutes (or multiples of it) to the start time and display it in an UILabel?<
Swift 3:
let minutes: TimeInterval = 1 * 60
let nowPlusOne = Date() + minutes
NSDate.init
with timeIntervalSinceNow
:
Ex:
let dateAfterMin = NSDate.init(timeIntervalSinceNow: (minutes * 60.0))
You can do date arithmetic by using NSDateComponents
. For example:
import Foundation
let comps = NSDateComponents()
comps.minute = 5
let cal = NSCalendar.currentCalendar()
let r = cal.dateByAddingComponents(comps, toDate: NSDate(), options: nil)
It is what you see when you try it in playground
Save this little extension:
extension Int {
var seconds: Int {
return self
}
var minutes: Int {
return self.seconds * 60
}
var hours: Int {
return self.minutes * 60
}
var days: Int {
return self.hours * 24
}
var weeks: Int {
return self.days * 7
}
var months: Int {
return self.weeks * 4
}
var years: Int {
return self.months * 12
}
}
Then use it intuitively like:
let threeDaysLater = TimeInterval(3.days)
date.addingTimeInterval(threeDaysLater)
Two approaches:
Use Calendar and date(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 a TimeInterval (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.
Swift 4:
// add 5 minutes to date
let date = startDate.addingTimeInterval(TimeInterval(5.0 * 60.0))
// subtract 5 minutes from date
let date = startDate.addingTimeInterval(TimeInterval(-5.0 * 60.0))
Swift 5.1:
// subtract 5 minutes from date
transportationFromDate.addTimeInterval(TimeInterval(-5.0 * 60.0))