fill the void

Posted
21 November 2009 @ 9pm

Tagged
development

No Comments Yet

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

No Comments Yet


There are no comments yet. You could be the first!

Leave a Comment