In-depth articles on technology shaping what comes next.

Doomsday Date Arithmetic Without Libraries

A 1960 doomsday headline hides a practical lesson: date arithmetic is easy to demo and hard to get right without libraries.

Mid-century study with chalkboard curves, calendar grids and a mechanical calculator
The old doomsday curve matters less than the calendar machinery needed to name its weekday.

A strange old headline has been circulating again: a 1960 Science item that pointed to Friday, 13 November 2026 and called it doomsday. The prophecy is not the interesting part for working programmers. The interesting part is that the date really is a Friday, and getting that answer forces you into date arithmetic: leap rules, month lengths, century exceptions, negative years, and the quiet difference between a formula that impresses people and code that survives production.

The paper behind the headline came from Heinz von Foerster and colleagues, and it has the flavor of a provocation. They looked at human population growth, argued it was worse than exponential, fitted a hyperbolic curve, and let the denominator run toward zero. The result was a singularity with a tabloid-perfect date. Historians and demographers can argue over how serious it was; it reads half like a warning and half like a joke told by someone who knew exactly how dramatic a Friday the thirteenth would sound.

What I keep coming back to is the craftsmanship hiding underneath. Before you can mock the prediction, verify the weekday. Before you can verify the weekday, decide which calendar you mean. Proleptic Gregorian? Actual civil dates in a given country? Astronomical year numbering or the no-year-zero convention historians use? Most of us reach for datetime, java.time, or chrono and move on. That is usually right. But the exercise of doing it without libraries is still one of the best little correctness workouts in programming, precisely because the rules are finite, old, and full of traps.

A Doomsday Headline Is a Calendar Problem

Start with the claim itself: 13 November 2026 is a Friday. You can check it in a REPL in seconds. The point of doing it by hand is not speed. It is to expose the model. A calendar is a state machine with irregular transitions: most months advance by thirty or thirty-one days, February changes shape in leap years, century years refuse to leap unless divisible by four hundred, and the whole pattern repeats on a four-hundred-year cadence in the Gregorian system. Once you see that cadence, weekday calculation stops being numerology and becomes modular arithmetic over a carefully designed cycle.

Conway's Doomsday method gives a memorable human algorithm. In each century there is an anchor weekday; for the 2000s it is Tuesday. For a year like 2026, take the last two digits, twenty-six. Divide by twelve to get two dozen years, remainder two, then add the leap years inside the remainder, zero. Two plus two plus zero is four; Tuesday plus four lands on Saturday. That is the year's "doomsday," the weekday shared by easy landmarks such as 4/4, 6/6, 8/8, 10/10, 12/12, the last day of February, and 7 November. If 7 November 2026 is Saturday, 13 November is six days later: Friday. Theatrical enough for a headline, mechanical enough for a napkin.

The mental method is elegant because it compresses the calendar into a few landmarks. But compression is also where bugs breed. The Doomsday algorithm assumes the Gregorian leap rule, assumes the common century anchors, assumes you are not crossing a calendar reform, and assumes you did not silently treat January and February like ordinary months. It is a beautiful local tool. It is not a date library.

Why Weekday Math Breaks in Real Code

Calendar bugs rarely announce themselves with fire. They show up as a renewal email sent a day early after a leap day, an invoice period that excludes the endpoint every February, a weekly job that drifts after a century boundary nobody expects to see, or a historian's dataset where year zero means one thing in ISO 8601 and another in a museum catalog. The gap between specification and implementation is exactly where these defects live, because everyone thinks the rule is obvious until two obvious rules collide.

The classic boundary case is the year 2000: divisible by one hundred, still a leap year because it is divisible by four hundred. The year 1900 was not. The year 2100 will not be. Plenty of hand-rolled leap checks remember year % 4 == 0 and stop there, which is correct for almost every year a startup cares about and wrong across a long enough horizon. Financial systems, archives, and infrastructure now live long enough that long horizons are no longer theoretical.

  • Leap-rule compression: y % 4 instead of the full Gregorian rule.
  • Month-numbering traps: human January is one, many APIs use zero, Zeller wants March first.
  • Negative-year semantics: astronomical year zero versus historical 1 BCE followed by 1 CE.
  • Week indexing: Sunday-first, Monday-first, Saturday-first in different formulas.
  • Calendar reform: adopting Gregorian rules before a region historically adopted them.
  • Integer division: C truncates toward zero, while calendar math often wants floor division.

Notice how many of those are representation errors rather than arithmetic errors. That is the deep lesson for language and library design. A date is not an integer with better branding. It is a value in a calendrical system, with validity rules, an epoch, a convention for years before the epoch, and a mapping to weekdays that depends on all of the above. Good APIs make invalid states awkward. Bad ones give you three integers and wish you luck.

Zeller, Doomsday, and the Shape of a Formula

Zeller's congruence is the older, crankier cousin of Conway's trick. For the Gregorian calendar it is often written with March as month 14, April as 15, and January and February treated as months 13 and 14 of the previous year. With day q, month m, year of century K, and zero-based century J, one common form is h = (q + floor(13(m+1)/5) + K + floor(K/4) + floor(J/4) + 5J) mod 7, where h = 0 means Saturday. It works. It is also a minefield of conventions.

There are multiple published variants, some with different weekday zero points, some for Julian calendars, some with terms added instead of subtracted. Copy one from a forum and you can get a formula that is right for 1901-2099 and wrong at the edges, or right only if your language floors integer division the way the author assumed. This is why I dislike presenting Zeller as production code. It is wonderful for understanding the structure: a linear day term, a month correction that approximates irregular lengths, a year term, leap corrections, and a century correction. It is less wonderful when a maintainer has to reverse-engineer which convention you used.

Conway's method optimizes for human memory. Zeller optimizes for algebraic neatness. Production code should optimize for auditability. Those are different goals. In a language-design sense, this is the difference between a clever macro and a boring function with invariants in the names. We need more boring functions with invariants in the names.

Interlocking calendar gears with a changing February gear inside century rings
A calendar is a machine: regular enough to model, irregular enough to punish shortcuts.

A Small Gregorian Core You Can Audit

If I need weekday logic in constrained code, my favorite baseline is Howard Hinnant's days-from-civil construction. It converts a Gregorian date to a serial day count relative to 1970-01-01, then weekday is modular arithmetic from a known Thursday. The implementation is short, but every constant has a reason. It avoids branchy month tables by shifting the year so March becomes the first month; leap day then sits at the end of the shifted year, where it disturbs nothing before it.

typedef long long i64;
/* Gregorian proleptic calendar; March is treated as the first month. */
static i64 days_from_civil(i64 y, int m, int d) {
y -= m <= 2;
i64 era = (y >= 0 ? y : y - 399) / 400;      /* floor-ish 400-year era */
int yoe = (int)(y - era * 400);              /* year of era, 0..399 */
int mp = m + (m > 2 ? -3 : 9);               /* Mar=0 ... Feb=11 */
int doy = (153 * mp + 2) / 5 + d - 1;        /* day of shifted year */
int doe = yoe * 365 + yoe / 4 - yoe / 100 + doy;
return era * 146097 + doe - 719468;          /* 1970-01-01 == 0 */
}
/* Returns 0=Sunday, 1=Monday, ... 6=Saturday. */
static int weekday_gregorian(i64 y, int m, int d) {
i64 z = days_from_civil(y, m, d);
int r = (int)((z + 4) % 7);                  /* 1970-01-01 was Thursday */
if (r < 0) r += 7;
return r;
}

The magic number 153 deserves respect. Across the shifted months March through February, lengths alternate in a pattern close to thirty and thirty-one days, and (153 * mp + 2) / 5 encodes cumulative days before each month without a lookup table. The expression 146097 is the number of days in a four-hundred-year Gregorian cycle: 146,000 days from four centuries, plus ninety-seven leap days. Subtracting 719468 recenters the count on the Unix epoch. None of this is mystical; it is the calendar spec distilled into arithmetic.

This is also where type choices matter. Use signed wide integers for serial days. Be explicit about proleptic Gregorian if that is what you implement. Decide whether out-of-range days like 31 April are rejected or normalized; I prefer rejection for civil dates because silent rollover hides upstream bugs. If you accept BCE input, say which numbering you use before the first subtraction happens. These sound like library concerns, but the same discipline applies inside a firmware blob or a stored procedure where nobody wants to admit dates are complicated.

Time Zones Are Not Calendar Arithmetic

A weekday is stable only after you pin down the time scale and location. A meeting at 00:30 in Tokyo is still the previous civil day in San Francisco. If your system stores instants, convert through a time-zone database before asking for weekday. If your system stores civil dates, do not casually convert them to instants without attaching a zone. The failure mode is subtle: two services can agree on the timestamp and disagree on the day.

This is why I separate three ideas in code reviews. An instant is a point on a physical timeline. A civil date is a legal or social label like 2026-11-13. A local time is the pairing of a civil label with a zone and its offset history. Weekday questions belong mostly to civil dates. Scheduling questions belong to instants plus zones. When code mixes them, every clean formula becomes haunted. Defensive engineering here means refusing to let a timestamp pretend it knows the user's calendar.

Leap seconds add another layer people love to drag into weekday debates. Ignore them for civil weekday math. Weekdays follow calendar days, not smoothed atomic time. If you smear leap seconds or use a monotonic clock for duration, fine, but do not let that leak into the question "is this Friday?" Friday is a social fact.

Tests That Deserve a Place in CI

Date code earns trust through adversarial fixtures, not vibes. Put the nasty cases next to the function. Test 1900-02-28 and 1900-03-01 as adjacent days with no leap day between. Test 2000-02-29 because it exists. Test 2099-12-31 rolling into 2100, where a four-year-only rule goes wrong. Test 1970-01-01 as Thursday if you use that epoch. Test negative years if you claim to support them, and test that you reject malformed input before arithmetic.

Property tests are useful if the properties are honest. Adding one day should advance weekday by one modulo seven for any valid date. Four hundred Gregorian years should contain 146,097 days and return to the same weekday. Within a non-leap century, doomsday-style landmarks should share a weekday only if your implementation is consistent. Do not test against a library generated by the same misunderstanding you are trying to avoid; pin expected answers from the standard or from independently derived tables.

A date routine is correct when its conventions are boring, explicit, and tested at the boundaries where the calendar changes its mind.

For the doomsday date itself, the expected answer is simple enough to hard-code in a comment: 2026-11-13 yields Friday under proleptic Gregorian rules. Then add the path around it: 2026-11-07 is a doomsday landmark Saturday, 2026-02-28 is Saturday, 2027-02-28 is Sunday after a common year, and 2028-02-29 exists because 2028 is divisible by four and not by one hundred. These little constellations catch off-by-one errors better than a random million cases.

Calendar tiles flipping states with red highlights at boundary cases
Good fixtures aim at boundaries: leap days, century years, epoch anchors, and malformed input.

The Old Lesson for New Models

The 1960 doomsday curve failed as demography because human systems are not passive points on a fitted line. Birth rates changed, policy changed, agriculture changed, urbanization changed, and the singularity stayed in the future where headlines keep it. That failure is useful for programmers too. A model can be internally consistent, historically grounded, and still wrong because the system under study edits the rules while you measure it.

Calendar arithmetic is the opposite luxury. The rules are slow, public, and mostly stable, which means correctness is achievable if we respect the specification. That makes dates a perfect training ground for a broader habit: name the model, isolate the core from time zones and IO, make conventions explicit, and test the places where continuity breaks. Whether you are writing C for an embedded RTC, a query planner, or a validation layer in a language runtime, the win is the same. Boring clarity beats clever certainty.

So yes, Friday the thirteenth is coming on schedule. No apocalypse required. The real scare is how easily a team can ship weekday logic that almost works, built from half-remembered congruences and assumptions nobody wrote down. Do the simple thing rigorously: implement the four-hundred-year cycle, reject impossible dates, keep instants separate from civil labels, and leave future maintainers a trail of constants they can verify. Doomsday makes a better unit test than a forecast.