Skip to content

Instantly share code, notes, and snippets.

@benjaminsnorris
Created May 17, 2016 23:21
Show Gist options
  • Save benjaminsnorris/106d0437cd844a76e8ba400d7d3ef38e to your computer and use it in GitHub Desktop.
Save benjaminsnorris/106d0437cd844a76e8ba400d7d3ef38e to your computer and use it in GitHub Desktop.
Rounding time
private func nearestPotentialStartTime(toTime time: NSDate) -> NSDate {
let calendar = NSCalendar.currentCalendar()
let components = calendar.components([.Era, .Year, .Month, .Day, .Hour, .Minute], fromDate: time)
let minutes = components.minute
let nextStartMark = (minutes % startInterval) + startInterval
let previousStartMark = nextStartMark - startInterval
let previousDelta = abs(minutes - previousStartMark)
let nextDelta = abs(minutes - nextStartMark)
components.minute = previousDelta <= nextDelta ? previousStartMark : nextStartMark
return calendar.dateFromComponents(components)!
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment