Under the Bridge

Snippet: Ordinal Days

So let’s say you have to index into an array of somethings for each day of the year — so you want an easy way to figure out what the appropriate index is for some arbitrary, date, like today. Like most things in Cocoa, it’s easy once you know how to sort out the ordinality of a day … but if you don’t, it may take you a while to figure out where. And here’s that where:

- (NSInteger)dayOfYearForDate:(NSDate *)date
NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSInteger day = [calendar ordinalityOfUnit:NSDayCalendarUnit inUnit:NSYearCalendarUnit forDate:date];
return day;

Now you know!