Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you calculate the day of the year for a specific date in Objective-C?

This is something I found myself spending hours to figure out and therefore want to share with you.

The question was: How do I determine the day of the year for a specific date?

e.g. January 15 is the 15th day and December 31 is the 365th day when it's not leap year.

like image 397
Godisemo Avatar asked Sep 09 '25 15:09

Godisemo


1 Answers

Try this:

NSCalendar *gregorian =
   [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSUInteger dayOfYear =
   [gregorian ordinalityOfUnit:NSDayCalendarUnit
     inUnit:NSYearCalendarUnit forDate:[NSDate date]];
[gregorian release];
return dayOfYear;

where date is the date you want to determine the day of the year for. The documentation on the NSCalendar.ordinalityOfUnit method is here.

like image 58
John Feminella Avatar answered Sep 12 '25 07:09

John Feminella