I am making an iPhone count down app and need to know how many times a weekend (like Saturday and Sundays ) will happen until the date the user sets.
An example is how could I find how many weekends will occur from now (Monday, August 6th) until next week? I know the answer is 1 weekend, but I need to be able to figure this out using code.
The closest I have gotten is using the NSDateComponents and NSCalender and doing something close to the following.
NSDateComponents *weekendsLeftComponents = [calendar components:NSWeekCalendarUnit
fromDate:targetDate
toDate:[NSDate date]
options:0];
But from there I have hit the dreaded coders wall of no passing.
My problem is not exactly knowing how to go about doing this. It sounds like an Array could work, but I am afraid the Array could get rather large as some of these "things" could go as long as a couple years. (I am making an app that finds out how many days, weekends, etc until a person graduates.) Also my audience is mainly kids to teens with iPods, older ones too. I don't know how full their memory (ram) can get before running out.
Thank you so much in advance,
Alex Kafer
It looks like your
fromDate
andtoDate
are backwards, assumingtargetDate
is in the future.Here's how I'd solve this problem.
Create a category on
NSCalendar
to count the number of times a specific weekday occurs between two dates:To implement this new method, we'll start by getting the year, month, day, and weekday of the
fromDate
:Next, we count how many days from
fromDate
to the next desired weekday:Note that
daysUntilDesiredWeekday
will be zero iffromDate
falls on the desired weekday.Now we can create an
NSDateComponents
representing the first desired weekday on or afterfromDate
:We update
fromDate
to be that first desired weekday, and return 0 if it's on or aftertoDate
:Next we count all the days (not just desired weekdays) from the updated
fromDate
totoDate
:We can divide that by the number of days in a week to count just the number of desired weekdays. Since we started counting from a desired weekday, any partial week remainder would also contain the desired weekday, so we need to round up:
We can test the method like this:
The output starts like this:
This looks correct according to the output of
cal 1 2012
:(Remember, the
toDate
is not counted, so there are 0 Mondays from 2012-1-1 to 2012-1-2, even though 2012-1-2 is a Monday.)