fill the void - bdunagan

21 Nov 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];
Previous LinkedIn Twitter GitHub Email Next