Sub topic 5
Comparing, Copying, and Doing Arithmetic on Dates
This chapter assumes you know that a Date wraps a millisecond time value. It also assumes you can build dates from components and ISO strings, and that you understand the difference between local and UTC getters and setters. The topics here are comparing dates correctly, avoiding accidental mutation, and adding days or months without landing on the wrong date.
Comparing Dates
A Date is an object, so === and == compare object identity, not the instant inside. Relational operators such as < and >= behave differently. They convert each Date to its time value with valueOf(), so they compare instants.
const a = new Date("2024-03-10T00:00Z");
const b = new Date("2024-03-10T00:00Z");
console.log(a === b); // false: two different objects
console.log(a.getTime() === b.getTime()); // true: same instant
console.log(a <= b, a < b); // true false
const dates = [new Date("2024-05-01Z"), new Date("2024-01-15Z"), new Date("2024-03-03Z")];
dates.sort((x, y) => x - y); // subtraction yields milliseconds
console.log(dates.map((d) => d.toISOString().slice(0, 10)));
// ["2024-01-15", "2024-03-03", "2024-05-01"]Copying Before You Mutate
Every Date setter changes the object in place. If two variables point to the same Date, changing it through one variable also changes what the other one sees.
const start = new Date(2024, 0, 1);
const alias = start; // same object
alias.setDate(5);
console.log(start.getDate()); // 5: start changed too
const copy = new Date(start.getTime()); // independent object
copy.setDate(10);
console.log(start.getDate(), copy.getDate()); // 5 10Write date helpers so they copy their input and return a new Date. This keeps them free of side effects.
Adding Days and Months
Setters normalize out-of-range values, so setDate(getDate() + n) crosses month and year boundaries correctly. Months are harder. Adding one month to January 31 asks for "February 31", which overflows to early March. Most applications expect the result to stop at the last day of the target month instead.
function addDays(date, days) {
const result = new Date(date.getTime());
result.setDate(result.getDate() + days);
return result;
}
function addMonthsClamped(date, months) {
const result = new Date(date.getTime());
const day = result.getDate();
result.setDate(1); // avoid overflow while changing month
result.setMonth(result.getMonth() + months);
const lastDay = new Date(result.getFullYear(), result.getMonth() + 1, 0).getDate();
result.setDate(Math.min(day, lastDay));
return result;
}
console.log(addDays(new Date(2024, 11, 30), 3).toDateString()); // "Thu Jan 02 2025"
console.log(addMonthsClamped(new Date(2024, 0, 31), 1).toDateString()); // "Thu Feb 29 2024"Day 0 of a month means "the last day of the previous month". That is why new Date(year, month + 1, 0) returns the last day of month.
Measuring Differences
Subtracting two dates gives a difference in milliseconds. To count calendar days, build both values with Date.UTC. Local days are not always 24 hours long, and the next chapter covers why.
const MS_PER_DAY = 86_400_000;
function daysBetween(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;
}
console.log(daysBetween(new Date(2024, 2, 1), new Date(2024, 3, 1))); // 31| Task | Correct approach | Common mistake |
|---|---|---|
| Equality | `a.getTime() === b.getTime()` | `a === b` |
| Sorting | `sort((x, y) => x - y)` | `sort()` |
| Copying | `new Date(d.getTime())` | `const c = d` |
| Add months | Clamp to the last day of the month | `setMonth(m + 1)` on day 31 |
Exercise
A function receives due, a Date, and runs due.setDate(due.getDate() + 7); return due;. Why could this cause bugs elsewhere, and how do you fix it?
Show answer
setDate changes the caller's Date object in place, so every other reference to that object moves forward by a week as well. Fix it by copying first: const result = new Date(due.getTime()); result.setDate(result.getDate() + 7); return result;.
Exercise
What does new Date(2023, 2, 31) become after setMonth(1), and what does addMonthsClamped(new Date(2023, 2, 31), -1) return?
Show answer
setMonth(1) asks for February 31, 2023. February 2023 has 28 days, so the date overflows to March 3, 2023. addMonthsClamped returns February 28, 2023.