Round NSDate to the nearest 5 minutes

cocoa, foundation, ios, objective-c

Solution

Take the minute value, divide by 5 rounding up to get the next highest 5 minute unit, multiply to 5 to get that back into in minutes, and construct a new NSDate.

NSDateComponents *time = [[NSCalendar currentCalendar]
                          components:NSHourCalendarUnit | NSMinuteCalendarUnit
                            fromDate:curDate];
NSInteger minutes = [time minute];
float minuteUnit = ceil((float) minutes / 5.0);
minutes = minuteUnit * 5.0;
[time setMinute: minutes];
curDate = [[NSCalendar currentCalendar] dateFromComponents:time];

Problem

For example I have ``` NSDate *curDate = [NSDate date]; ``` and its value is 9:13 am. I am not using year, month and day parts of curDate. What I want to get is date with 9:15 time value; If I have time value 9:16 I want to advance it to 9:20 and so on. How can I do that with NSDate?

Original source

Related problems