⚡ Why Comparing Two Dates With == Almost Never Does What You Expect
Two `Date` objects representing the exact same moment in time compare as NOT equal with `==` (or `===`) – which surprises people expecting date comparison to work like number or string comparison, because in JavaScript, `Date` is an object, and `==`/`===` between two objects compares REFERENCE identity, never their actual represented values.
🔎 The Problem
const d1 = new Date('"'"'2026-09-06T10:00:00Z'"'"');
const d2 = new Date('"'"'2026-09-06T10:00:00Z'"'"');
console.log(d1 == d2); // false
console.log(d1 === d2); // false
// Both represent the EXACT same instant, but they'"'"'re two separate
// object instances in memory - == and === only ever check "is this
// literally the same object reference", never "do these represent the
// same moment in time".
✅ Fix: Compare the Underlying Timestamp, Not the Objects
- `d1.getTime() === d2.getTime()` (or the shorthand `+d1 === +d2`) compares the actual millisecond timestamp each `Date` wraps – this is the correct way to check if two dates represent the same moment.
- For comparing whether one date is before/after another, use the relational operators directly on the Date objects (`d1 < d2`, `d1 > d2`) – unlike `==`, these DO trigger JavaScript’s implicit numeric conversion for Date objects and work correctly, which is a genuinely confusing asymmetry worth remembering.
⚠️ The Same Rule Applies to Any Object, Not Just Dates
- This isn’t Date-specific behavior – `{} == {}` is also false for the identical reason, even with visually identical content, because object equality in JavaScript is always about reference, never structural content, unless you write that comparison yourself.
- Libraries like `date-fns` or `Luxon` provide explicit `isEqual()`/comparison helpers that read more clearly than `.getTime()` calls scattered through a codebase, if date comparisons show up often enough to be worth the dependency.
Two dates can point at the exact same moment and still fail `==` – because JavaScript was never asked to compare moments, only to compare objects, and those are different questions.
