Article View: comp.lang.c.moderated
Article #2235Re: BEST date <=> daynum converter?
From: tenthumbs
Date: Mon, 11 Mar 1996 12:27
Date: Mon, 11 Mar 1996 12:27
60 lines
2527 bytes
2527 bytes
heading_anthony@jpmorgan.com (Anthony Heading) wrote:
> Hi,
>
> What's the speediest algorithm for conversion between day-month-year
> dates and "days since 1janXX"? I'd like to find something really fast
> which only need cope with dates between say 1970 and 2100.
>
> One rather nice thing I found was the method ascribed to Fliegel
> and Van Flandern (CACM 1968); an (untested) implementation attached.
> It avoids using floating point, which is nice. Many other routines
> seem to, but I always worry about doing essentially discrete maths with
> floats. Is that paranoid?
>
> But perhaps the lack of any conditionals below is excessive. There must
> be something faster/simpler.
>
> Any thoughts?
>
> [stuff deleted]
>
1) Make sure that your ints are big enough. January 1, 2000 = 2451545.
2) In cal2days, the assignment l = (j - 14)/12 assumes that division of
a negative number by 12 rounds towards zero. In other words, "l" = -1
for January and February and 0 otherwise. This probably isn't a problem,
but you never know. It's easy to replace this with a conditional
statement.
3) Since you're only interested in the 20th and 21th century, the
constant 4800 in the term 1461*(i + 4800 + l)/4 can be brought out of
the expression.
4) Similarly, - 3*((i + 4900 + l)/100)/4 is a constant.
Here's a new version that will work for dates from 1 March 1900 through
28 February 2100:
static int cal2days(date_t *d)
{
register int i = d->year;
register int j = d->month;
register int k = d->day;
if (j <= 2)
i--, j += 12;
return (d->dnum = 1461*i/4
+ 367*(j - 2)/12
+ k + 1721074);
}
One further speed improvement is to replace the term 367*(j - 2)/12 by a
table lookup. If you do that, there would be only one multiplication and
one division. Hard to beat that.
Days2cal is about as good as you can get.
Hope this helps.
Technical Details
Message-ID:
<4i168c$fk@solutions.solon.com>Path:
arc1-ca.pugleaf.net!solon.com!not-for-mailReferences:
<4hv04d$j80@solutions.solon.com>Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!solon.com!not-for-mail From: tenthumbs@buttercup.cybernex.net Newsgroups: comp.lang.c.moderated Subject: Re: BEST date <=> daynum converter? Date: 11 Mar 1996 06:27:56 -0600 Organization: Digital Solutions Sender: clc@solutions.solon.com Approved: clc@solutions.solon.com Message-ID: <4i168c$fk@solutions.solon.com> References: <4hv04d$j80@solutions.solon.com> NNTP-Posting-Host: solutions.solon.com X-Newsreader: Forte Agent .99d/16.182 X-Nntp-Posting-User: (Unauthenticated) X-Trace: 826515320/13391 X-Nntp-Posting-Host: cnj1-217.cybernex.net