Date Coversion Routines

Dale Schumacher dal at midgard.mn.org
Wed Oct 12 08:37:31 AEST 1988


In article <1483 at maccs.McMaster.CA> gordan at maccs.UUCP () writes:
|In article <7618 at rpp386.Dallas.TX.US> jfh at rpp386.Dallas.TX.US (The Beach Bum) writes:
|-In article <44100014 at hcx2> danr at hcx2.SSD.HARRIS.COM writes:
|->>   Does anyone have a routine to change back and forth between
|->>seconds from 19xx to a Year, Month, Day sort of Date?  
|
|Well, astronomers tend to worry about this sort of thing a lot.
|
|The September (or May?) 1984 issue of Sky and Telescope magazine devoted
|some space to this problem, publishing two BASIC (yuck) programs that
|convert from year/month/day to Julian date, and vice versa.  The Julian
|date is simply the number of days since January 1, 4713 BC.
|
|The two functions are astonishingly short, using some sort of floating
|point trickery.  They seemed to work when I tested them.  Conversion to
|C is left as an exercise for the reader.

I don't think floating point is required.  I know that it isn't for the
formula that I have.  I haven't compared the to closely enough (nor do I
want to) to determine if they are identical.  In any case, the following
source code from dLibs (which is public domain) calculated julian date
very nicely, and it's supposed to be accurate to +/- 4 million years!

long julian_date(time)
	register struct tm *time;
/*
 *	Number of days since the base date of the Julian calendar.
 */
	{
	register long c, y, m, d;

	y = time->tm_year + 1900;	/* year - 1900 */
	m = time->tm_mon + 1;		/* month, 0..11 */
	d = time->tm_mday;		/* day, 1..31 */
	if(m > 2)
		m -= 3L;
	else
		{
		m += 9L;
		y -= 1L;
		}
	c = y / 100L;
	y %= 100L;
	return( ((146097L * c) >> 2) +
		((1461L * y) >> 2) +
		(((153L * m) + 2) / 5) +
		d +
		172119L );
	}

PS.  If you define your days of the week as:
	char *day[] = { "Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat" };
     the day-of-week is:
	day[(julian_date(t) + 1L) % 7L];
     (ie.  the julian day 0 is a Monday.)



More information about the Comp.lang.c mailing list