Article View: comp.os.msdos.programmer
Article #7239finding the day of week from the date
From: Tom Reingold
Date: Fri, 21 Jun 1991 17:56
Date: Fri, 21 Jun 1991 17:56
83 lines
2526 bytes
2526 bytes
Here is a sample program that finds the day of the week, given the
date. It works for this century only. Making it work for any century
is "left as an exercise to 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@samadams.princeton.edu OR ...!princeton!samadams!tr
"Warning: Do not drive with Auto-Shade in place. Remove
from windshield before starting ignition."
Technical Details
Message-ID:
<tr.677526990@samadams>Path:
arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!mips!spool.mu.edu!uwm.edu!linac!att!princeton!newross!samadams!trShow Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!utzoo!utgpu!news-server.csri.toronto.edu!cs.utexas.edu!swrinde!mips!spool.mu.edu!uwm.edu!linac!att!princeton!newross!samadams!tr From: tr@samadams.princeton.edu (Tom Reingold) Newsgroups: comp.os.msdos.programmer Subject: finding the day of week from the date Message-ID: <tr.677526990@samadams> Date: 21 Jun 91 17:56:30 GMT Sender: news@newross.Princeton.EDU (USENET News System) Organization: Princeton University, Dept. of Computer Science Lines: 83