Richard J. Ross III Richard J. Ross III - 1 year ago 163
Objective-C Question

NSDate get year/month/day

How can I get the year/month/day of a

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
's year/month/day. Is there any other solution?

Answer Source

Because this is apparently my most popular answer, I'll try to edit it to contain a little bit more information.

Despite its name, NSDate in and of itself simply marks a point in machine time, not a date. There's no correlation between the point in time specified by an NSDate and a year, month, or day. For that, you have to refer to a calendar. Any given point in time will return different date information based on what calendar you're looking at (dates are not the same in both the Gregorian and Jewish calendars, for instance), and while the Gregorian calendar is the most widely used calendar in the world - I'm assuming - we're a little biased that NSDate should always use it. NSDate, luckily, is far more bipartisan.

Getting date and time is going to have to pass through NSCalendar, as you mentioned, but there's a simpler way to do it:

NSDateComponents *components = [[NSCalendar currentCalendar] components:NSCalendarUnitDay | NSCalendarUnitMonth | NSCalendarUnitYear fromDate:[NSDate date]];

That generates an NSDateComponents object containing the day, month, and year from the current system calendar for the current day. (Note: this isn't necessarily the current user-specified calendar, just the default system one.)

Of course, if you're using a different calendar or date, you can easily change that. A list of available calendars and calendar units can be found in the NSCalendar Class Reference. More information about NSDateComponents can be found in the NSDateComponents Class Reference.

For reference, accessing individual components from the NSDateComponents is rather easy:

NSInteger day = [components day];
NSInteger month = [components month];
NSInteger year = [components year];

You just have to be mindful: NSDateComponents won't contain valid information for any fields you ask for unless you generated them with that valid information (i.e. request NSCalendar to provide that information with NSCalendarUnits). NSDateComponents contain no reference information in and of themselves - they're just simple structures that hold numbers for you to access. If you want to also get an era, for instance, out of NSDateComponents, you'll have to feed the generator method from NSCalendar with the NSCalendarUnitEra flag.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download