Date to Day-of-Week Conversion (Question)
Tom Reingold
tr at samadams.princeton.edu
Sat Jun 22 04:15:00 AEST 1991
This will work for this century. I'll leave fixing it for any century
as an exercise for the reader.
#include <stdio.h>
#include <sys/types.h>
#include <time.h>
static int monlens[] = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
static char *daytab[] = { "Sat", "Sun", "Mon", "Tue", "Wed", "Thu", "Fri" };
static int keys[12];
void initkeys();
main(argc, argv)
int argc;
char *argv[];
{
int day;
time_t t;
struct tm *tp;
if (argc != 3 && argc != 4) {
yuck:
fprintf(stderr, "usage: %s month date [year]\n", argv[0]);
exit(1);
}
t = time(&t);
tp = localtime(&t);
tp->tm_mon = atoi(argv[1]) - 1;
tp->tm_mday = atoi(argv[2]);
if (argc == 4)
tp->tm_year = atoi(argv[3]);
initkeys(tp->tm_year);
if (tp->tm_mon == -1 || tp->tm_mday == 0 || tp->tm_year == 0)
goto yuck;
if (tp->tm_mday > monlens[tp->tm_mon]) {
fprintf(stderr, "%s: invalid date\n", argv[0]);
exit(2);
}
day = dateof(tp);
printf("%02d/%02d/%02d is a %s\n", tp->tm_mon + 1, tp->tm_mday,
tp->tm_year, daytab[day]);
exit(0);
}
dateof(tp) /* return day of week: Saturday=0, ..., Friday=6 */
struct tm *tp;
{
int crap;
crap = tp->tm_year + tp->tm_mday + keys[tp->tm_mon] +
((int) tp->tm_year / 4);
return(crap % 7);
}
isleap(year)
int year;
{
if (((year % 4 == 0) && (year % 100 != 0)) || (year % 400 == 0))
return(1);
return(0);
}
void initkeys(n)
int n;
{
int i;
/* This generates a table. I could hard code it, but I wanted
to show what the table means. */
if (isleap(n))
keys[0] = 0, monlens[1] = 29;
else
keys[0] = 1;
for (i = 1; i < 12; i++)
keys[i] = (monlens[i-1] + keys[i-1]) % 7;
}
--
Tom Reingold
tr at samadams.princeton.edu OR ...!princeton!samadams!tr
"Warning: Do not drive with Auto-Shade in place. Remove
from windshield before starting ignition."
More information about the Comp.lang.c
mailing list