< previous page page_110 next page >

Page 110
(continued)
Listing 6.1
           This routine will calculate a date, given an 'n' of, say, 5,
           and the DOW will be match the 'dow_index' given, but if the
           date should fall outside the given month (and/or given year),
           then this routine returns an error condition.
   2. This routine works in three basic steps:
      2.1. Find the DOW of the first day of the given month and year.
      2.2. Find the date of the first DOW matching the input DOW.
      2.3. Find the date of the 'n' th DOW matching the input DOW.
*/


#include "scdtl_2.h"


struct DATE_INFO Nth_DOW_of_month (int n, int dow_index, int month, int year)
{
   int index, diff;
   double jd;
   struct DATE_INFO date;


   date = make_date (0, 0, 0);
   if ( (n < 1) || (n > 5) )
      return (date);


   if ( (dow_index < 0) || (dow_index > 6) )
      return (date);
   if ( (month < 1) || (month > 12) )
      return (date);


   date = make_date (year, month, 1);
   jd = date_to_JD0 (&date);
   index = day_of_week_index_JD0 (jd);
   diff = (dow_index - index);


/*
   If diff = 0 below, 1st of the month is 1st DOW already, no adjustment
   is required. The 'diff' is the adjustment from the 1st of the month
   required to get to the first DOW matching the 'dow_index' given.
*/


   if (diff < 0)
      jd += (double) (7 + diff);
   else
      {
      if (diff > 0)
         jd += (double) (diff);
      }


/*
    The condition 'n < 1' has already been eliminated as an error,
    so the 'else' below covers the condition of 'n > 1'.
*/


   if (n == 1)
      date = JD0_to_date (jd);
   else
      {
      jd += (double) ((n - 1) * 7);
      date = JD0_to_date (jd);
      }

 
< previous page page_110 next page >