views:

281

answers:

1

How can I get the year/month/day of a NSDate object, given no other information? I realize that I could probably do this with something similar to this:

NSCalendar *cal = [[NSCalendar alloc] init];
NSDateComponents *components = [cal components:0 fromDate:date];
int year = [components year];
int month = [components month];
int day = [components day];

But that seems to be a whole lot of hassle for something as simple as getting a NSDate's year/month/day. Is there any other solution?

+2  A: 

Yeah, it's a little bit of hassle, but that's the only way of getting this information without manually calculating it yourself from NSDate's -timeIntervalSince1970 method.

If you're going go with NSCalendar, though, you might want to change your code a bit to make it easier to use:

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit fromDate:[NSDate date]];
NSInteger day = [components day];    
NSInteger month = [components month];
NSInteger year = [components year];

Also, if you have to pass around these date components a lot, I'd recommend wrapping them in a struct. Just a tip.

itaiferber
A correction to this, the first line should have NSDayCalendarUnit instead of NSWeekCalendarUnit.
whitehawk
You're right, my mistake.
itaiferber