Date-Routines for C/UNIX ? HELP
mccaugh at s.cs.uiuc.edu
mccaugh at s.cs.uiuc.edu
Tue Sep 12 09:53:00 AEST 1989
I tried mailing to Mathias, but no luck...anyway, here (at least) is the
C code for day-of-week given the date as MMDDYYYY:
#include <stdio.h>
#include <time.h>
#include <ctype.h>
void weekday();
static char *names[] = {"Sunday", "Monday", "Tuesday", "Wednesday",
"Thursday", "Friday", "Saturday"};
main (argc,argv)
int argc;
char *argv[];
{
if(argc!=2)
fprintf(stderr, "usage: weekday mmddyyyy\n");
else weekday(argv[1]);
}
void weekday(date) /* given: date = "mmddyyyy" */
char *date; /* print: day of the week */
{
char *dp, month[3], day[3], year[5];
int mm, dd, yyyy, reg_yrs, lp_yrs,
i, yrs, days, days_more;
long secs;
static int reg_days[12] = {0,31,59,90,120,151,181,212,243,273,304,334},
lp_days[12] = {0,31,60,91,121,152,182,213,244,274,305,335};
struct tm *tp;
dp = date; /* save */
month[0] = *dp++; month[1] = *dp++; month[2] = '\0'; /* get "mm" */
mm = atoi(month); /* into mm as int */
day[0] = *dp++; day[1] = *dp++; day[2] = '\0'; /* get "dd" */
dd = atoi(day); /* into dd as int */
for(i=0; i<4; i++) year[i] = *dp++;
year[4] = '\0'; /* get "yyyy" into */
yyyy = atoi(year); /* yrs as an int */
yrs = yyyy - 1970;
lp_yrs = yrs/4; if(yrs%4 == 3) lp_yrs++; reg_yrs = yrs - lp_yrs;
days = 365*reg_yrs + 366*lp_yrs; /* = #(days) until given year */
if(yyyy%4 == 0) /* yyyy = leap-year */
days_more = lp_days[--mm]; /* = #(days) from start of yyyy */
else days_more = reg_days[--mm]; /* until month mm */
days += days_more + dd; /* = total of days altogether */
secs = 86400*days; /* = #(secs) of whole days since 1/1/70 */
tp = localtime(&secs);
printf("%s falls on %s.\n", date, names[tp->tm_wday]);
return;
}
e.g.: weekday 091119189 reports that the date is a Monday.
Hope this helps!
Scott McCaughrin
Dept. of Computer Science
University of Illinois
Urbana, Illinois. USA
More information about the Comp.lang.c
mailing list