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

#import 

@interface NSDate (IVDateComponents)

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

#import "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.


via blog.vucica.net

4 thoughts on “Getting year, month and day out of NSDate

Leave a Reply

Your email address will not be published.

 

What is 2 + 13 ?
Please leave these two fields as-is:
IMPORTANT! To be able to proceed, you need to solve the following simple math (so we know that you are a human) :-)

This site uses Akismet to reduce spam. Learn how your comment data is processed.