Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Initialize NSDate with custom date

Tags:

objective-c

I'm looking for something like:

NSDate *date = [[NSDate alloc] initWithYear:1984 month:10 Day:8];

Is there a way to do something like this?

Thanks!

like image 851
Carlo Avatar asked Oct 05 '10 06:10

Carlo


1 Answers

I wrote a category for this task. NSDate is missing a lot of useful methods.

@interface NSDate (missingFunctions) 
+ (NSDate *)dateWithYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day;
@end


@implementation NSDate (missingFunctions)

+ (NSDate *)dateWithYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day {
    NSCalendar *calendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
    NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
    [components setYear:year];
    [components setMonth:month];
    [components setDay:day];
    return [calendar dateFromComponents:components];
}   
@end
like image 172
Matthias Bauch Avatar answered Oct 25 '22 11:10

Matthias Bauch