# How to invert number of days since 1 JAN 2000

Given the day of a year $d_y$ and the year $y$, it is straightforward to calculate the number of days since 1 JAN 2000:

$D = d_y-1+(y-2000)*365+floor((y-2000)/4)-floor((y-2000)/100)+floor((y-2000)/400)$

But now, given $D$, I would like to invert and calculate $d_y$ and $y$. Anyone know of a way to do this that does not boil down to counting and comparing? Thanks.

-

Every 400-year period contains exactly 146,097 days, so by dividing and taking remainder you can reduce the problem to finding a date between 2000 and 2399.

First, if $D\le 366$, it's in 2000. That's reasonable to treat as a special case, because 2000 is the only multiple of 100 within our period that's a leap year.

Otherwise subtract $366$ from $D$; we're now looking for a date between 2001 and 2399 and counting January 1 2001 as day 0. Any 100-year period in this interval contains 36,524 days; by dividing with remainder once more we can reduce the problem to find a date between 2001 and 2100.

Now, any 4-year period between 2001 and 2100, except the last, contains 1461 days. The last one has only 1460 days, but since $D$ at this stage can never be 36525 we can ignore that difference. Just divide by 1461 and the remainder will point to a date between 2001 and 2004.

Finally divide by 365; if the quotient is 4 we're at December 31 2004; otherwise the quotient plus 2001 is the year and the remainder is the day within the year (which is 0-based, so add one if you want an 1-based day number).

-
Thanks! Nice! If I can ask, have you seen this kind of thing before, or just sat down and figured it out? – bob.sacamento Oct 23 '13 at 15:46
@bob.sacamento: I've sat down and figured it out before. :-) – Henning Makholm Oct 23 '13 at 19:44