try maadee try maadee - 1 year ago 139
Swift Question

How to add minutes to current time in swift

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(
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*

Rob Rob
Answer Source

Two approaches:

  1. Use calendar:

    let calendar = NSCalendar.currentCalendar()
    let date = calendar.dateByAddingUnit(.Minute, value: 5, toDate: startDate, options: [])     // used to be `.CalendarUnitMinute`

    By the way, that's iOS 8 and later. If you want to support iOS 7, too, you'd do:

    let calendar = NSCalendar.currentCalendar()
    let components = NSDateComponents()
    components.minute = 5
    let date = calendar.dateByAddingComponents(components, toDate: startDate, options: nil)
  2. Just use dateByAddingTimeInterval to add a certain number of seconds:

    let date = startDate.dateByAddingTimeInterval(5.0 * 60.0)

Bottom line, dateByAddingTimeInterval is easiest, but if you ever get to adding days, months, etc., you want to use the calendrical calculations because those adjust for daylight savings, whereas dateByAddingTimeInterval doesn't.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download