3

How can I find the count of a specific weekday occurring between two NSDates?

I have searched for quite a while but came up with only solution in which number of total weekdays have been counted, not only the one specific week day.

jscs
  • 63,694
  • 13
  • 151
  • 195

2 Answers2

6

The idea of the following code is to compute the first occurrence of the given weekday after the start date, and then compute the number of weeks remaining to the end date.

NSDate *fromDate = ...;
NSDate *toDate = ...;
NSUInteger weekDay = ...; // The given weekday, 1 = Sunday, 2 = Monday, ...
NSUInteger result;

// Compute weekday of "fromDate":
NSCalendar *cal = [NSCalendar currentCalendar];
NSDateComponents *c1 = [cal components:NSWeekdayCalendarUnit fromDate:fromDate];

// Compute next occurrence of the given weekday after "fromDate":
NSDateComponents *c2 = [[NSDateComponents alloc] init];
c2.day = (weekDay + 7 - c1.weekday) % 7; // # of days to add
NSDate *nextDate = [cal dateByAddingComponents:c2 toDate:fromDate options:0];

// Compare "nextDate" and "toDate":
if ([nextDate compare:toDate] == NSOrderedDescending) {
    // The given weekday does not occur between "fromDate" and "toDate".
    result = 0;
} else {
    // The answer is 1 plus the number of complete weeks between "nextDate" and "toDate":
    NSDateComponents *c3 = [cal components:NSWeekCalendarUnit fromDate:nextDate toDate:toDate options:0];
    result = 1 + c3.week;
}

(The code assumes that a week has seven days, which is true for the Gregorian calendar. If necessary, the code could probably generalized to work with arbitrary calendars.)

Martin R
  • 529,903
  • 94
  • 1,240
  • 1,382
  • 2
    The mentioned generalization should be as simple as replacing the hard 7 with `[cal rangeOfUnit:NSWeekdayCalendarUnit inUnit:NSWeekCalendarUnit forDate:fromDate]`. – jscs Jul 16 '15 at 23:02
0
NSDateComponents *components = [gregorianCalendar components:NSDayCalendarUnit fromDate:[NSDate date] toDate:[NSDate date]];
//pass different date in fromDate and toDate column.
Atulkumar V. Jain
  • 5,102
  • 9
  • 44
  • 61
h.kishan
  • 681
  • 6
  • 20
  • 2
    The question is (if I understand it correctly) how many e.g. Sundays are between two given dates. – Martin R Jul 30 '13 at 11:08
  • where am I gonna specify day , i.e (Monday or Tuesday or Friday etc.) ??. because I wanna count occurrence of a specific weekday only.. – DemonicPossessions1991 Jul 30 '13 at 11:13
  • @MartinR : yes of course, and not only sundays. it can be any day of week. e.g Monday or Tuesday or any other day, but yeah, that's right, you got me correctly.. – DemonicPossessions1991 Jul 30 '13 at 11:17
  • IMO, this may be not the best way to do it, just give a try. 1. get the difference between the two dates and 2. Iterate through the date's day [To get the Day From Date](http://stackoverflow.com/a/4745207/1059705) in loop and then compare the day with your DAY, – Bala Jul 30 '13 at 11:36