1

Given three integers, representing a day, month and year, what code would assemble those integers into a date object?

Moshe
  • 57,511
  • 78
  • 272
  • 425

2 Answers2

4

You should look at NSDateComponents:

int y = 2011;
int m = 1;
int d = 15;


NSDateComponents *dc = [[NSDateComponents alloc] init];
[dc setYear:y];
[dc setMonth:m];
[dc setDay:d];

NSLog(@"%@: %@", [[dc date] class], [dc date]);
Eimantas
  • 48,927
  • 17
  • 132
  • 168
  • 1
    +1 for being correct in principle, but the implementation is wrong. `NSDateComponents` does not have a `-date` method, though you can convert one into an `NSDate` using `NSCalendar`. – Dave DeLong Jan 20 '11 at 08:38
  • I double-checked `NSDateComponents` class documentation (iOS 4.2 docset) and I see `-date` method right between `calendar` and `day` methods. Am I missing something? – Eimantas Jan 20 '11 at 09:03
  • Ah, I've checked the Mac OS X 10.6 docset and `NSDateComponents` does not have `-date` method indeed. The question has iOS tag, so I figured it's for Cocoa Touch. – Eimantas Jan 20 '11 at 09:14
0

NSDateFormatter uses the Unicode Standard for parsing date strings into dates. So, format your integers into a date string and then use and NSDateFormatter to parse it:

// assume year, month and day are integers that are formatted properly and don't
// include invalid ranges
NSString* dateString = [NSString stringWithFormat:@"%04d %02d %02d", year, month, day];
NSDateFormatter* formatter = [[NSDateFormatter alloc] init];
// Choose a format of YEAR MONTH DATE per the standard
[formatter setDateFormat:@"yyyy MM dd"];
NSDate* date = [formatter dateFromString:dateString];
[formatter release];

You can set the format string to whatever format floats your boat, as long as you use the Unicode Standard (linked above) and you convert your integers into the same format (obviously).

Jason Coco
  • 77,985
  • 20
  • 184
  • 180