Path: utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!zaphod.mps.ohio-state.edu!uwm.edu!linac!att!princeton!newross!samadams!tr From: tr@samadams.princeton.edu (Tom Reingold) Newsgroups: comp.lang.c Subject: Re: Date to Day-of-Week Conversion (Question) Message-ID: Date: 21 Jun 91 18:15:00 GMT References: <1991Jun19.170753.593@tse.uucp> <1991Jun20.164534.28592@druid.uucp> Sender: news@newross.Princeton.EDU (USENET News System) Distribution: na Organization: Princeton University, Dept. of Computer Science Lines: 83 This will work for this century. I'll leave fixing it for any century as an exercise for the reader. #include #include #include 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@samadams.princeton.edu OR ...!princeton!samadams!tr "Warning: Do not drive with Auto-Shade in place. Remove from windshield before starting ignition."