⚡ Fix a Temporal Polyfill Rounding a Date Wrong at a Boundary
Calling .round() or .until()/.since() on the Temporal API’s polyfill without an explicit roundingMode defaults to halfExpand, a rounding rule that behaves differently on negative durations than most developers’ mental model of Math.round() built from years of working with positive numbers only. A duration that lands exactly on a half-unit boundary – common right at a date subtraction’s sign flip – can round in a direction that surprises anyone who assumed the default would just match Math.round().
⚡ The Problem
const start = Temporal.PlainDate.from("2026-03-10");
const end = Temporal.PlainDate.from("2026-03-08");
// Negative duration, exactly 2 days - no roundingMode specified,
// so it falls back to the default "halfExpand" behavior, which
// treats the sign of the duration differently than Math.round()
// would for the equivalent positive number.
const diff = end.until(start, { smallestUnit: "days" })
.round({ smallestUnit: "weeks", roundingMode: undefined });
✅ Fix: Make the Rounding Mode an Explicit Choice
- Pass roundingMode explicitly – trunc for a display-only truncated countdown, halfExpand only when you genuinely want conventional rounding – instead of relying on the default, since the default behaves differently on negative durations than most developers expect from Math.round().
- Normalize a duration’s sign before rounding when only its magnitude matters, taking the absolute duration first rather than rounding a signed duration and then taking the absolute value afterward, since the two orders of operations don’t always agree exactly at a boundary.
- Add a unit test for a date pair that produces an exact half-unit duration, not just a pair a few days or weeks apart, since boundary-rounding bugs by definition only show up exactly at the boundary.
🚨 Why This Is Dangerous
- A countdown or “time ago” display that’s off by one unit only at exact half-boundaries is the kind of bug that passes every manual test someone tries by hand, then gets reported by confused users days apart with none of them easy to reproduce on demand.
A rounding mode you never chose is still a rounding mode – it’s just one the polyfill picked for you, and not always the one you’d have picked yourself.
