Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rounding of NSdate to nearest hour in iOS

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?

like image 908
Sumit Patel Avatar asked Jun 10 '13 07:06

Sumit Patel


3 Answers

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)
    }
}
like image 53
Colin Basnett Avatar answered Nov 03 '22 01:11

Colin Basnett


Use this method

- (NSDate*) nextHourDate:(NSDate*)inDate{
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *comps = [calendar components: NSEraCalendarUnit|NSYearCalendarUnit| NSMonthCalendarUnit|NSDayCalendarUnit|NSHourCalendarUnit fromDate: inDate];
    [comps setHour: [comps hour]+1]; //NSDateComponents handles rolling over between days, months, years, etc
    return [calendar dateFromComponents:comps];
}

This will give you the date in next hour for the inDate

like image 9
Lithu T.V Avatar answered Nov 02 '22 23:11

Lithu T.V


 func nextHourDate() -> NSDate? {
    let calendar = NSCalendar.currentCalendar()
    let date = NSDate()
    var minuteComponent = calendar.components(NSCalendarUnit.MinuteCalendarUnit, fromDate: date)
    let components = NSDateComponents()
    components.minute = 60 - minuteComponent.minute
    return calendar.dateByAddingComponents(components, toDate: date, options: nil)
}
like image 4
Osman Alpay Avatar answered Nov 02 '22 23:11

Osman Alpay