Sub topic 5
Comparing, Copying, and Doing Arithmetic on Dates
This chapter assumes you know that a Date wraps a single millisecond time value, that months are zero-based, and that local and UTC getters and setters are two views of the same instant. Here we use that model to compare dates, avoid unwanted mutation, and add or subtract time without silent errors.
Comparing Dates
A Date is an object. The relational operators <, >, <=, and >= convert both sides to primitives through valueOf(), which returns the time value, so they compare instants correctly. The equality operators == and === do not convert two objects. They compare references, so two dates for the same instant are "not equal".
const a = new Date("2024-05-01T00:00:00Z");
const b = new Date("2024-05-01T00:00:00Z");
console.log(a === b); // false: different objects
console.log(a == b); // false: still a reference comparison
console.log(a.getTime() === b.getTime()); // true: same instant
console.log(+a === +b); // true: unary plus calls valueOf
console.log(a < b, a <= b); // false trueCompare getTime() values whenever you test for equality. Code that uses getTime() for every comparison shows what it means more clearly than code that mixes operators.
Sorting, minimum, and maximum
Subtracting two dates gives a number of milliseconds, which is exactly what an Array.prototype.sort comparator needs. Math.min and Math.max also convert their arguments to numbers, so they return time values that you can wrap in a new Date.
const dates = [
new Date("2024-03-01T00:00Z"),
new Date("2023-12-25T00:00Z"),
new Date("2024-01-15T00:00Z"),
];
dates.sort((x, y) => x - y); // ascending; use y - x for descending
console.log(dates.map((d) => d.toISOString().slice(0, 10)));
// ["2023-12-25", "2024-01-15", "2024-03-01"]
const latest = new Date(Math.max(...dates));
console.log(latest.toISOString()); // "2024-03-01T00:00:00.000Z"Never sort dates without a comparator. The default sort converts elements to strings, and toString() output begins with the weekday name, so the order comes out wrong.
Invalid Dates in comparisons
An Invalid Date has a time value of NaN, and every comparison involving NaN returns false. That means bad < good and bad >= good are both false, and a sort comparator returning NaN produces an unpredictable order. Validate dates first:
const isValidDate = (d) => d instanceof Date && !Number.isNaN(d.getTime());
console.log(isValidDate(new Date("2024-02-30T00:00Z"))); // false: day 30 doesn't exist in the ISO string form
console.log(isValidDate(new Date(2024, 1, 30))); // true: component form rolls over to March 1The two results differ because the ISO parser rejects out-of-range fields, while the component constructor rolls overflow into the next month.
Copying and the Mutation Trap
Every set* method changes the Date it is called on. It returns the new time value as a number, not the date. Both facts cause bugs when a date is shared between variables or passed into a function.
function nextDay(d) {
d.setDate(d.getDate() + 1); // mutates the caller's object
return d;
}
const due = new Date(2024, 4, 31); // May 31, local time
const reminder = nextDay(due);
console.log(due === reminder); // true: one object, two names
console.log(due.getMonth(), due.getDate()); // 5 1 -> due is now June 1
const x = new Date(2024, 0, 1);
const result = x.setDate(5);
console.log(typeof result); // "number", not a DateTo fix this, copy first and then mutate the copy. new Date(d) and new Date(d.getTime()) both make an independent copy. structuredClone(d) also works. A pure function never touches its input:
function addDaysLocal(date, days) {
const result = new Date(date.getTime());
result.setDate(result.getDate() + days);
return result;
}
const start = new Date(2024, 4, 31);
const later = addDaysLocal(start, 1);
console.log(start.getDate(), later.getDate()); // 31 1Two Kinds of Arithmetic
"Add a day" can mean two different things, and you need to decide which one you mean before writing the code.
| Kind | Meaning | How to do it | Affected by DST? |
|---|---|---|---|
| Elapsed duration | Exactly N milliseconds later (timers, timeouts, "90 minutes from now") | `new Date(d.getTime() + ms)` | No: the time value moves by exactly ms |
| Calendar arithmetic | Same wall-clock time on a later day or month (due dates, billing) | `setDate`, `setMonth`, or their UTC versions | Local setters keep the wall-clock time, so the elapsed time can be 23 or 25 hours |
const MINUTE = 60 * 1000;
const meeting = new Date("2024-07-04T16:30:00Z");
const ends = new Date(meeting.getTime() + 90 * MINUTE);
console.log(ends.toISOString()); // "2024-07-04T18:00:00.000Z"Days roll over correctly, months do not
Setters normalize overflow, so setDate(getDate() + 40) correctly moves into the next month or year. That makes day arithmetic safe. Month arithmetic is not safe this way: adding one month to January 31 asks for February 31, which rolls over to March 2 or 3. Most business rules expect the result to stay at the end of the month instead. To get that, set the day to 1, move the month, and then clamp the day:
function addMonthsUTC(date, months) {
const result = new Date(date.getTime());
const day = result.getUTCDate();
result.setUTCDate(1); // avoid overflow while the month changes
result.setUTCMonth(result.getUTCMonth() + months);
// Day 0 of the following month is the last day of this month.
const lastDay = new Date(
Date.UTC(result.getUTCFullYear(), result.getUTCMonth() + 1, 0)
).getUTCDate();
result.setUTCDate(Math.min(day, lastDay));
return result;
}
console.log(addMonthsUTC(new Date("2024-01-31T00:00Z"), 1).toISOString()); // "2024-02-29T00:00:00.000Z"
console.log(addMonthsUTC(new Date("2024-03-31T00:00Z"), -1).toISOString()); // "2024-02-29T00:00:00.000Z"
console.log(addMonthsUTC(new Date("2023-01-31T00:00Z"), 13).toISOString()); // "2024-02-29T00:00:00.000Z"The "day 0" trick (Date.UTC(year, month + 1, 0)) gives you the length of any month, leap years included, without a lookup table.
Differences Between Dates
b - a gives elapsed milliseconds. Dividing that by 86,400,000 does not reliably count calendar days. Times of day distort the result: 23:00 to 01:00 the next morning is one calendar day apart but only two hours elapsed. A daylight saving change in between can also make a local day 23 or 25 hours long. To count calendar days, project each local date onto UTC midnight and subtract the results:
const MS_PER_DAY = 24 * 60 * 60 * 1000;
function calendarDaysBetween(a, b) {
const utcA = Date.UTC(a.getFullYear(), a.getMonth(), a.getDate());
const utcB = Date.UTC(b.getFullYear(), b.getMonth(), b.getDate());
return (utcB - utcA) / MS_PER_DAY; // always an integer: UTC has no DST
}
const lateNight = new Date(2024, 2, 1, 23, 0);
const earlyMorning = new Date(2024, 2, 2, 1, 0);
console.log((earlyMorning - lateNight) / MS_PER_DAY); // ~0.083
console.log(calendarDaysBetween(lateNight, earlyMorning)); // 1The same projection answers "is this the same day?" Compare the two UTC-midnight values with ===. The next chapter covers the daylight saving cases in detail.
Common Errors
| Symptom | Cause | Fix |
|---|---|---|
| Two equal dates compare unequal | `===` compares object references | Compare `getTime()` values |
| Original date changed unexpectedly | A setter ran on a shared object | Copy with `new Date(d.getTime())` first |
| `TypeError: x.toISOString is not a function` | A setter's numeric return value was used as a Date | Return the copied Date, not the setter result |
| Jan 31 + 1 month = Mar 2 | Day overflow during `setMonth` | Clamp to the last day of the target month |
| Day count is 0.958 or 1.04 | Elapsed ms divided across a DST change | Use `calendarDaysBetween` |
| Sort order is random or alphabetical | No comparator, or Invalid Dates in the array | Use `(a, b) => a - b` and validate first |
Exercise
A teammate writes const end = start; end.setDate(end.getDate() + 7); and then logs both start and end. What do they see, and what is the one-line fix?
Show answer
Both variables show the same date, seven days after the original start, because end and start point to the same object and setDate mutated it. The fix is to copy before mutating: const end = new Date(start.getTime());.
Exercise
Write isSameLocalDay(a, b) that returns true when two Dates fall on the same calendar day in the runtime's local time zone, regardless of time of day.
Show answer
const isSameLocalDay = (a, b) => a.getFullYear() === b.getFullYear() && a.getMonth() === b.getMonth() && a.getDate() === b.getDate(); Comparing the components avoids both reference equality and millisecond differences. An equivalent version compares Date.UTC(a.getFullYear(), a.getMonth(), a.getDate()) with the same expression for b using ===.
Exercise
What does addMonthsUTC(new Date("2024-08-31T00:00Z"), 1) return, and what would a naive setUTCMonth(getUTCMonth() + 1) return instead?
Show answer
addMonthsUTC returns 2024-09-30T00:00:00.000Z, because September has 30 days and the day is clamped. The naive version asks for September 31, which rolls over to 2024-10-01T00:00:00.000Z.