Calculating the 2nd Tuesday of the Month

As many of you know I am in the middle of rewriting from Cold Fusion to WebDev. Since it is a reminder site, a lot of the functionality revolves around dates.

For instance one of the features we support is scheduling a reminder for the nth weekday of the month, such as the 2nd Tuesday of the month. I am finding it very easy to write these types of functions in WX. Here is the code for the function:


PROCEDURE GetDayofMonth(TheDate is Date,DayofTheWeek is int,WeekNumber is int)

IF NOT DateValid(TheDate) OR DayofTheWeek < 1 OR DayofTheWeek > 7 OR WeekNumber < 1 OR WeekNumber > 4 THEN
   RESULT ("")

TheDate = FirstDayOfMonth(TheDate)

FOR x = 1 _TO_ 6
   IF DateToDay(TheDate) = DayofTheWeek THEN
   TheDate..Day += 1

IF WeekNumber > 1 THEN
   TheDate..Day += ((WeekNumber-1) * 7)


The function takes 3 parameters

  1. TheDate = Any day in the month we want the result for.
  2. DayofTheWeek = WX standard days of the week (Monday=1, Tuesday = 2, etc.)
  3. WeekNumber = 1 through 4 (2 for the 2nd Tuesday of the Month)

The first if statement just makes sure that it is called with sane values and returns an empty string if not.

Next the WX FirstDayofMonth function resets the date to the first.

The FOR Loop increments the day by one until we get to the first day of the week specified (Monday, Tuesday, etc.) . Another approach would be to do some math on the Day of the Week for the 1st versus the Day of the Week requested, which would perform a little faster. Since I am not doing tons of calculations a minute, I opted for code readability instead.

The the final IF statement increments the date by the number of weeks if it was not 1 (the 2nd Tuesday).

And finally the date is returned.

Now to calculate the correct date for reminders that repeat “Every 2nd Tuesday of the Month”, it just two lines of code

CurrentReminderDate..Month += 1
CurrentReminderDate =GetDayofMonth(CurrentReminderDate,2,2)

NOTE: When incrementing dates be sure to always use the += syntax, that way months, years, etc. automatically rollover correctly. The below code will not handle the rollover to a new year correctly when it reaches December.

CurrentReminderDate..Month = CurrentReminderDate..Month + 1

Now, back to your regular schedule program….

Leave a Reply

Please log in using one of these methods to post your comment: Logo

You are commenting using your account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s