Calendar Functions
Dave Lewis
dml at loral.UUCP
Thu Sep 11 02:47:34 AEST 1986
In article <206 at cascade.STANFORD.EDU> leeke at cascade.UUCP (Steven D. Leeke)
writes:
>Could someone please give me some pointers to functions for creating
>calendars? e.g. for any day from 1900 to as far in the future as possible.
>Actual code would be GREATLY appreciated - C preferred.
>
Here's a collection of calendar functions; writing a main() driver
function should be trivial. These were originally assignments for a Pascal
class (what the hey, an easy 4 credits with an A+) and I rewrote them in
C for the hell of it. Good for contrasting Pascal and C - things I had to
work around in Pascal came out as straight code in C.
/* Determines whether a given year is a leap year
*/
leapyear (year)
int year;
{
if (year % 4 == 0 && (year % 100 != 0 || year % 400 == 0))
return (1);
else
return (0);
}
/* Returns #days in month given month and year, taking
* leap years into account for February.
*/
daysinmonth (month, year)
int month, year;
{
if (month == 2) /* Is it February? */
if (leapyear (year)) /* If so, is it a leap year? */
return (29); /* 29 days in Feb in leap year */
else
return (28); /* 28 days if not */
else{
if (month > 7) /* Is it August -> December? */
month++; /* Invert even/odd state if so */
if (month & 1) /* Odd months have 31 days */
return (31);
else
return (30); /* Even months have 30 days */
}
}
/* Determines whether a given date is valid
*/
validdate (month, day, year)
int month, day, year;
{
if (month < 1 || month > 12 || day < 1 ||
day > daysinmonth (month, day, year) ||
year < 1583 || year > 9999)
return (0);
else
return (1);
}
/* Given a valid date (month, day, and year) Zeller will
* return an integer representing the day of week that
* date will fall on. 0 = Sunday, 6 = Saturday.
*/
zeller (month, day, year)
int month, day, year;
{
int century;
month -= 2; /* Years start on March 1 so adjust standard date */
if (month < 1) {
month += 12;
year--;
}
century = year / 100;
year = year % 100;
return (((2.6 * month - 0.1) + day + year + year / 4
+ century / 4 - century * 2) % 7);
}
These functions will work for any date between March 1, 1583 and December 31,
9999. Have fun!
-------------------------------
Dave Lewis Loral Instrumentation San Diego
hp-sdd --\ ihnp4 --\
sdcrdcf --\ bang --\ kontron -\
csndvax ---\ calmasd -->-->!crash --\
celerity --->------->!sdcsvax!sdcc3 --->--->!loral!dml (uucp)
dcdwest ---/ gould9 --/
When the government runs it, it's called a Lottery.
When somebody else runs it, it's called a Numbers Racket.
-------------------------------
More information about the Comp.lang.c
mailing list