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?
@IBAction func timePickerClicked(sender: UIDatePicker) {
var dateFormatter = NSDateFormatter()
dateFormatter.timeStyle = NSDateFormatterStyle.ShortStyle
var dateStr = dateFormatter.stringFromDate(startTime.date)
let sttime = dateStr
startTimeDisplay.text = dateStr
}
// How to advance time by 5 minutes for each section based on the start time selected and display time
// section 1 = start time + 5
// section 2 = start time + 10*
Save this little extension:
Then use it intuitively like:
Swift 3:
Swift 4:
// add 5 minutes to date
// subtract 5 minutes from date
Swift 5.1:
You can use Calendar's method
to add any
Calendar.Component
to anyDate
. You can create a Date extension to add x minutes to yourUIDatePicker
's date:Xcode 8 and Xcode 9 • Swift 3.0 and Swift 4.0
Then you can just use the extension method to add minutes to the sender (UIDatePicker):
Playground testing:
In case you want unix timestamp
You can do date arithmetic by using
NSDateComponents
. For example:It is what you see when you try it in playground