Wowers, I see many answers here, but many are long or hard to understand, so I will try to drop my 2 cents in case this helps. The NSCalendar class provides the necessary functionality in a safe and concise way. Here is a solution that works for me, without multiplying the second interval of seconds, rounding, or anything else. NSCalendar takes into account leap days / years and other oddities in time and date. (Swift 2.2)
let calendar = NSCalendar.currentCalendar() let rightNow = NSDate() let interval = 15 let nextDiff = interval - calendar.component(.Minute, fromDate: rightNow) % interval let nextDate = calendar.dateByAddingUnit(.Minute, value: nextDiff, toDate: rightNow, options: []) ?? NSDate()
It can be added to the extension to NSDate , if necessary, or as a free-form function that returns a new instance of NSDate , no matter what you need. Hope this helps everyone who needs it.
Swift 3 Update
let calendar = Calendar.current let rightNow = Date() let interval = 15 let nextDiff = interval - calendar.component(.minute, from: rightNow) % interval let nextDate = calendar.date(byAdding: .minute, value: nextDiff, to: rightNow) ?? Date()
BJ Miller Jun 30 '16 at 2:00 p.m. 2016-06-30 14:00
source share