tags:

views:

39

answers:

1

Hello, 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!

+3  A: 

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 currentCalendar];
    NSDateComponents *components = [[[NSDateComponents alloc] init] autorelease];
    [components setYear:year];
    [components setMonth:month];
    [components setDay:day];
    return [calendar dateFromComponents:components];
}   
@end
fluchtpunkt
Works like a charm. Thank you :).
Carlo
It isn't missing. It's intentionally not there. The theory is that a hypothetical `+[NSDate dateWithYear:month:day:]` would make developers presuppose that everybody used the Gregorian calendar. Better, in Apple's mind, to split apart moment-in-time manipulation (`NSDate`) from real-world calendar manipulation (`NSCalendar` and `NSDateComponents`.)
Jonathan Grynspan
thx for the explanation, was never thinking of it that way.
fluchtpunkt
@fluchtpunkt: You should read the date programming guide for the rationale of why those functions are missing. Basically an NSDate just a particular point in time. Things like years, months and days within a month are meaningless except in the context of a particular calendar. http://developer.apple.com/library/ios/#documentation/cocoa/Conceptual/DatesAndTimes/DatesAndTimes.html%23//apple_ref/doc/uid/10000039i
JeremyP