views:

822

answers:

2

Hi all,

This is a bit odd, but is it possible to use an NSCalendar (or any component, for that matter) to figure out what the date of the next "first tuesday of the month" would be?

For example, today is Thursday March 25, 2010. The next "first tuesday of the month" would be on April 6. Likewise, if I were looking for the next "first tuesday of the month" on April 1, it would still be on April 6.

How would you do this?

Thanks very much!!!!!

A: 

Unfortunately I can not verify the incapacity of this code, but some should look like this:

NSDateComponents *components = [[NSDateComponents alloc] init];
[components setWeekday:2]; // Monday
[components setMonth:5]; // May
[components setYear:2008];
[components setWeekdayOrdinal:1]
NSCalendar *gregorian = [[NSCalendar alloc]
                         initWithCalendarIdentifier:NSGregorianCalendar];
NSDate *date = [gregorian dateFromComponents:components];

For samples and detail info see this guide

Victor
Thanks but this just hard-codes a date. I need to be able to dynamically figure out what the date I'm looking for is...
Bjorn S.
Yes of course. This is just sample :-)
Victor
This won't work. You need to include `[components setWeekdayOrdinal:1];`.
Ole Begemann
You are right. This code also does not contain the actual computation of the date, but this is just the direction for the implementation of the work function.
Victor
+2  A: 

The code below calculates the first Tuesday of a given month/year combination. It's written in MacRuby because that is what I just tried it with, but you should have no problems to convert it to proper Objective-C, it's just a different syntax (I love MacRuby for quickly trying out an idea):

dc = NSDateComponents.alloc.init
# Set month to April 2010
dc.setYear 2010
dc.setMonth 4

dc.setWeekday 3 # 1 = Sunday, 2 = Monday, ...
dc.setWeekdayOrdinal 1 # We want the first weekday of the month

cal = NSCalendar.alloc.initWithCalendarIdentifier NSGregorianCalendar
date = cal.dateFromComponents dc
date.description # => "2010-04-06 00:00:00 +0200"

I leave it to you to determine the "next first Tuesday" from a given date: do the calculation for the month of the current date first and if the result is in the past, do it again for the following month. Use -[NSCalendar components:fromDate:] to get the month/day combo of a given NSDate.

Ole Begemann
simply fantastic!
Bjorn S.