8

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!

Carlo
  • 25,602
  • 32
  • 128
  • 176

1 Answers1

20

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
Matthias Bauch
  • 89,811
  • 20
  • 225
  • 247
  • 7
    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 Oct 05 '10 at 08:05
  • 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 Oct 05 '10 at 11:00
  • This code will return incorrect results if current system calendar is non-Gregorian. Please change calendar initialization to `[[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease]`. – yakovlev Nov 06 '11 at 13:44
  • And you should be explicit and specify whether the date is relative to where the user is currently located (`[calendar setTimeZone:[NSTimeZone defaultTimeZone]]`) or absolute (`[calendar setTimeZone:[NSTimeZone timeZoneWithName:@"GMT"]]`). – yakovlev Nov 06 '11 at 14:16
  • All of that rationale is negated by a `year:month:day:calendarIdentifier:` method. No excuses for not having a convenience method here in my opinion. Too much boilerplate for your standard "give me a specific date" need. – Tom Redman Oct 24 '13 at 17:32