iphoneiosnsdatenscalendarnsdatecomponents

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?


Solution

  • 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