As many of you know I am in the middle of rewriting pcReminder.com 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 ("") END TheDate = FirstDayOfMonth(TheDate) FOR x = 1 _TO_ 6 IF DateToDay(TheDate) = DayofTheWeek THEN BREAK END TheDate..Day += 1 END IF WeekNumber > 1 THEN TheDate..Day += ((WeekNumber-1) * 7) END RESULT TheDate
The function takes 3 parameters
- TheDate = Any day in the month we want the result for.
- DayofTheWeek = WX standard days of the week (Monday=1, Tuesday = 2, etc.)
- 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….