Counting the days, revisited
The algorithm for converting Gregorian dates to Julian Day numbers was previously written but has been improved since. The main formula counts days before the year's start, adjusting for leap days and the unusual alignment of January and February at the end of the previous year. This adjustment allows the leap day in year 4 to be counted correctly at the beginning of the adjusted year.
The function is then able to utilize more of its output data type's range. The next part corrects the number of leap years before the current year, similar to the Julian leap year calculation but requiring a more complex approach. Modern compilers can turn divisions into simple shifts, making the code more efficient. Finally, the number of days in the current (adjusted) year before the start of the month is calculated.
The expression is improved by converting it into a multiply-and-shift operation, rather than using compiler optimizations that may not be as efficient. The epoch can be adjusted based on the desired starting point, such as the MJD or Unix epochs. Unsigned integers are recommended for these calculations to avoid misleading results for dates before year 1.
Additionally, a faster leap year test is proposed, which checks divisibility by 25 and 16, or by 4 but not 25, using fewer comparisons and potentially improving performance.
Written by urgent.news from Lobsters's reporting — not their text. Machine-written; read the original for the full account.

