Rounding of NSdate to nearest hour in iOS

Sumit Patel picture Sumit Patel · Jun 10, 2013 · Viewed 7.3k times · Source

I have data in the format

time: 13:52, 10:30, 11:48

etc

I would like to round to the nearest hour.

like for 13:52 -> 14:00 , 10:30 -> 11:00 and 11:48 -> 12:00.

How can I do that with NSDate?

Answer

Colin Basnett picture Colin Basnett · May 2, 2017

Here's a Swift 3.0 implementation that gets the nearest hour, using a Date extension:

extension Date {
    func nearestHour() -> Date? {
        var components = NSCalendar.current.dateComponents([.minute], from: self)
        let minute = components.minute ?? 0
        components.minute = minute >= 30 ? 60 - minute : -minute
        return Calendar.current.date(byAdding: components, to: self)
    }
}