bdunagan

Brian Dunagan

November 21 2009
Cocoa Tip: Extend NSDate

Categories are a seemless way to extend existing Cocoa classes like NSDate. In my post on relative dates, I see if two timestamps land on the same day, by zeroing out the hour/minute/second components. Recently, while working on an iPhone app, I refactored it, converting it from a transformer into a category.

@implementation NSDate (Utilities)
- (NSDate *)dateAtMidnight {
	// Initialize the calendar and flags.
	NSCalendar *calendar = [NSCalendar currentCalendar];
	unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit |
	NSDayCalendarUnit | NSWeekdayCalendarUnit;

	// Set date's hour/minute/second to zero.
	NSDateComponents *comps = [calendar components:unitFlags fromDate:self];
	[comps setHour:0];
	[comps setMinute:0];
	[comps setSecond:0];
	return [calendar dateFromComponents:comps];
}
@end
iPhone WordPress Theme with WPtouch Cocoa Tip: Extend NSNumber
LinkedIn GitHub Email