Path: utzoo!utgpu!news-server.csri.toronto.edu!rpi!usc!samsung!sol.ctr.columbia.edu!emory!att!news.cs.indiana.edu!ux1.cso.uiuc.edu!phil From: phil@ux1.cso.uiuc.edu (Phil Howard KA9WGN) Newsgroups: comp.lang.c Subject: Re: Request for simple date routines. Message-ID: <1991Apr14.233518.13747@ux1.cso.uiuc.edu> Date: 14 Apr 91 23:35:18 GMT References: <1991Apr9.234255.143@mprgate.mpr.ca> Organization: University of Illinois at Urbana Lines: 45 stone@mars.mpr.ca (Darren Stone) writes: >Hi. Just a simple request I hope somebody can >easily pull out of their toolbox... >(1) >I'd like a function which, given a date, returns >0..6 representing the day of the week of the date. The following is written on the fly and NOT TESTED. All good programmers test everything before using it anyway, so why should I be worried. You might want to also add validity checking, especially for user input. For a year from 1901 to 2099, subtract 1900 from the year giving 1 to 199: yy = year - 1900; Now add the year value divided by 4: yy += ( yy / 4 ); Now add a special number for the month: int mnums[12] = { 0,3,3,6,1,4,6,2,5,0,3,5 }; yy += mnums[ month-1 ]; /* month is 1..12 */ Special case for leap years: if ( (year%4)==0 && month<3 ) yy -= 1; Add the date (1..31): yy += date; Now just take the number modulo 7: char *weekday[7] = { "sun","mon","tue","wed","thu","fri","sat" }; day = weekday[ yy%7 ]; >I really don't care at all about efficiency, but >they must work absolutely reliably for +/- several >hundred years (taking into account the leap-year >rules). Actually, what are the leap year rules? >Something about evenly divisible by 4, except >not by 100, except by 400? It gets more complicated beyond this range. The leap year rules for the 100/400/4000 years is: Years divisible by 100 are NOT leap years UNLESS they are divisible by 400 and not 4000. Thus 2000 and 2400 are leap years and 2100 and 4000 are not. -- /***************************************************************************\ / Phil Howard -- KA9WGN -- phil@ux1.cso.uiuc.edu | Guns don't aim guns at \ \ Lietuva laisva -- Brivu Latviju -- Eesti vabaks | people; CRIMINALS do!! / \***************************************************************************/