holographix holographix - 1 year ago 57
Objective-C Question

calculate the number of weeks in a daterange

I need to make some time-based statistics over logs that goes on over the course of a year,
all I need to do is the count of the (solar) weeks inside a determined range of dates.

i.e. I need to calculated how many weeks have been occurred between the 1st of Aug 2011 and the 3rd of Sep 2012. and things like this.

I've had the idea of counting the days between the two dates and then divide by 7, but that doesn't count the fact that I could be in between weeks an in this case the value wold not be correct / precise.

Anybody had faced a similar issue before?

Answer Source

I assume you have your two dates in NSDates (date1 and date2). Then call

NSCalendar *calendar = [NSCalendar currentCalendar];
//declare your unitFlags
int unitFlags = NSWeekCalendarUnit;

NSDateComponents *dateComponents = [calendar components:unitFlags fromDate:date1  toDate:date2 options:0];

int weeksInBetween = [dateComponents week];

Hope that helps