September 24 2010
Cocoa Tip: NSDate, to the nearest 15 minutes
Unfortunately, NSDate doesn’t have a “round” selector like roundToNearestQuarterHour. But it does have NSDateComponents available. Just a couple lines of code using that handy class, and I can get the desired result: a date in Cocoa, rounded to the nearest 15 minutes. Just add the code below to the nearest NSDate category.
- (NSDate *)dateToNearest15Minutes {
// Set up flags.
unsigned unitFlags = NSYearCalendarUnit| NSMonthCalendarUnit | NSDayCalendarUnit | NSWeekCalendarUnit | NSHourCalendarUnit | NSMinuteCalendarUnit | NSSecondCalendarUnit | NSWeekdayCalendarUnit | NSWeekdayOrdinalCalendarUnit;
// Extract components.
NSDateComponents *comps = [[NSCalendar currentCalendar] components:unitFlags fromDate:self];
// Set the minute to the nearest 15 minutes.
[comps setMinute:((([comps minute] - 8 ) / 15 ) * 15 ) + 15];
// Zero out the seconds.
[comps setSecond:0];
// Construct a new date.
return [[NSCalendar currentCalendar] dateFromComponents:comps];
}