holographix
holographix

Reputation: 2557

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?

Upvotes: 1

Views: 1833

Answers (3)

Nuzhdin Vladimir
Nuzhdin Vladimir

Reputation: 1822

NSDateComponents *difference = [[NSCalendar currentCalendar] components:NSCalendarUnitDay
                                                               fromDate:startDate]
                                                                 toDate:endDate]
                                                                options:0];
NSInteger weeksDiffCount = (((NSInteger)[difference day])/7);

Hope it helps.

Upvotes: 0

JustSid
JustSid

Reputation: 25318

NSCalendar is the class that you should take a at into. It allows you to get the NSDateComponents from two dates using the components:fromDate:toDate:options: method, while dealing with all the messed up time stuff for you.

Upvotes: 1

Boris Prohaska
Boris Prohaska

Reputation: 912

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

Upvotes: 6

Related Questions