Tag Archives: NSDate

Getting year, month and day out of NSDate

For some reason, Apple didn’t provide an easy way to extract day, month and year from an NSDate. Probably because they think OS X shouldn’t be Western-centric and presume a Gregorian calendar (although they could have simply extracted this data from current locale). Here is a simple category that allows just that.

// NSDate+IVDateComponents.h

 

@interface NSDate (IVDateComponents)

@property (nonatomic, readonly) NSInteger year;
@property (nonatomic, readonly) NSInteger month;
@property (nonatomic, readonly) NSInteger day;
@end
// NSDate+IVDateComponents.m

 "NSDate+IVDateComponents.h"


@implementation NSDate (IVDateComponents)
-(NSInteger)year
{
	unsigned units = NSYearCalendarUnit;
	NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
	NSDateComponents *components = [calendar components:units fromDate:self];
	
	return [components year];
}
-(NSInteger)month
{
	unsigned units = NSMonthCalendarUnit;
	NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
	NSDateComponents *components = [calendar components:units fromDate:self];
	
	return [components month];
}
-(NSInteger)day
{
	unsigned units = NSDayCalendarUnit;
	NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
	NSDateComponents *components = [calendar components:units fromDate:self];
	
	return [components day];
}
@end

Note that this code is very Western-centric and always presumes the Gregorian calendar. Sue me.