Day of week algorithm wanted for "C"

Bob Stout Bob.Stout at p6.f506.n106.z1.fidonet.org
Wed Nov 22 17:44:21 AEST 1989


In an article of <20 Nov 89 02:02:37 GMT>, (Lenny Tropiano) writes:

 >I need a function that accepts a month, a day, and a year ... and returns
 >the day-of-the-week (ie. Sunday, Monday, etc..)
------------------------------- Cut Here -------------------------------------
/*
** scalar date routines    --    public domain by Ray Gardner
** These will work over the range 1/01/01 thru 14699/12/31
*/

int isleap (yr)
unsigned yr;
{
   return yr % 400 == 0 || (yr % 4 == 0 && yr % 100 != 0);
}

static unsigned months_to_days (month)
unsigned month;
{
   return (month * 3057 - 3007) / 100;
}

static long years_to_days (yr)
unsigned yr;
{
   return yr * 365L + yr / 4 - yr / 100 + yr / 400;
}

long ymd_to_scalar (yr, mo, day)
unsigned yr, mo, day;
{
   long scalar;
   scalar = day + months_to_days(mo);
   if ( mo > 2 )                         /* adjust if past February */
      scalar -= isleap(yr) ? 1 : 2;
   yr--;
   scalar += years_to_days(yr);
   return scalar;
}

void scalar_to_ymd (scalar, pyr, pmo, pday)
long scalar;
unsigned *pyr, *pmo, *pday;
{
   unsigned n;                /* compute inverse of years_to_days() */
   for ( n = (scalar * 400L) / 146097; years_to_days(n) < scalar; )
      n++;                          /* 146097 == years_to_days(400) */
   *pyr = n;
   n = scalar - years_to_days(n-1);
   if ( n > 59 ) {                       /* adjust if past February */
      n += 2;
      if ( isleap(*pyr) )
         n -= n > 62 ? 1 : 2;
   }
   *pmo = (n * 100 + 3007) / 3057;  /* inverse of months_to_days() */
   *pday = n - months_to_days(*pmo);
}

int scalar_to_day(scalar)
long scalar;
{
    return (int)(scalar % 7L);      /* 0 = Sunday, 1 = Monday, etc. */
}
------------------------------- Cut Here -------------------------------------



More information about the Comp.lang.c mailing list