tags:

views:

454

answers:

3

I'm trying to get the number of days in a current year.

When I try the solution on http://stackoverflow.com/questions/1179945/number-of-days-in-the-current-month-using-iphone-sdk, and replace NSMonthCalendarUnit by NSYearCalendarUnit, I still get the number of days for that month.

Does anyone know how I should do this?

Thanks in advance for your help.

A: 

Look at using NSDate's timeIntervalSinceDate:

That will give you the number of seconds between two dates. So find the time interval between the first and last day of the year and then convert the seconds to days.

ordord00
+3  A: 

If you're only going to use the Gregorian Calender, you can calculate it manually.

http://en.wikipedia.org/wiki/Leap%5Fyear#Algorithm

if year modulo 400 is 0 then leap
 else if year modulo 100 is 0 then no_leap
 else if year modulo 4 is 0 then leap
 else no_leap
kubi
A: 

I finally came up with a solution that works. What I do is first calculate the number of months in the year and then for each month calculate the number of days for that month.

The code looks like this:

NSUInteger days = 0;
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *today = [NSDate date];
NSDateComponents *components = [calendar components:NSYearCalendarUnit fromDate:today];
NSUInteger months = [calendar rangeOfUnit:NSMonthCalendarUnit
                                   inUnit:NSYearCalendarUnit
                                  forDate:today].length;
for (int i = 1; i <= months; i++) {
    components.month = i;
    NSDate *month = [calendar dateFromComponents:components];
    days += [calendar rangeOfUnit:NSDayCalendarUnit
                           inUnit:NSMonthCalendarUnit
                          forDate:month].length;
}

return days;

It is not as neat as I would have hoped for but it will work for any calendar such as the ordinary gregorian one or the islamic one.

Godisemo