Skip to content
jshacks.dev
Fundamentals

JavaScript Date Pitfalls and How to Avoid Each One

Date counts months from zero, parses date-only strings as UTC, mutates through setters and mishandles daylight saving. See each trap and the safe habit.

8 min read
Summarize in AI
Flat illustration of an editor window full of code, with the JavaScript, TypeScript and npm logos.

Every JavaScript developer has a story about a Date that was off by one: a birthday that showed the day before, a report that skipped a month, a timer that fired an hour late twice a year. The object is not random. It is a thin wrapper around a millisecond timestamp with local-time getters and setters bolted on, and each of its traps follows from a design decision made in the first version of the language. This post lists the traps that cause real bugs, with output from Node.js 24, and gives the safe habit for each. The snippets set the time zone at runtime with process.env.TZ, so the output is the same wherever you run them. The replacement is described in the post on Temporal, and the whole subject is mapped in the guide to dates and times.

Months start at zero

The month argument and getMonth() use 0 for January. Days and years do not.

JavaScript
process.env.TZ = "UTC";

const june = new Date(2026, 5, 15);
const january = new Date(2026, 0, 31);

console.log(june.getMonth(), june.getDate(), june.getFullYear());
console.log(june.toISOString());
console.log(january.toISOString());
console.log(new Date(2026, 12, 1).toISOString());
console.log(new Date(2026, 0, 0).toISOString());
console.log(new Date(2026, 2, 0).getDate());
Text
5 15 2026
2026-06-15T00:00:00.000Z
2026-01-31T00:00:00.000Z
2027-01-01T00:00:00.000Z
2025-12-31T00:00:00.000Z
28

Month 5 is June, so a bare 5 meaning May is a bug that no error catches. Out-of-range values roll over: month 12 is January of the next year, and day 0 is the last day of the previous month. That last behavior is a handy trick, since new Date(2026, 2, 0).getDate() gives the number of days in February, and it is also why an off-by-one in a month calculation produces a plausible wrong date and not an error. A named constant or a lookup table of month names removes the ambiguity in code that reads.

Date-only strings are UTC, date-time strings are local

The same-looking strings parse in different zones. A date-only ISO string is read as UTC midnight, and a date-time string with no offset is read as local time.

JavaScript
process.env.TZ = "America/New_York";

const dateOnly = new Date("2026-05-06");
const dateTime = new Date("2026-05-06T00:00:00");
const withOffset = new Date("2026-05-06T00:00:00Z");

console.log(dateOnly.toISOString());
console.log(dateTime.toISOString());
console.log(dateOnly.getTime() === withOffset.getTime());

console.log(dateOnly.getDate(), dateTime.getDate());
console.log(dateOnly.toLocaleDateString("en-US"));
console.log(dateOnly.toLocaleDateString("en-US", { timeZone: "UTC" }));
Text
2026-05-06T00:00:00.000Z
2026-05-06T04:00:00.000Z
true
5 6
5/5/2026
5/6/2026

In New York, the date-only string is 8 p.m. on May 5 local time, so getDate() returned 5 for a value that was typed as May 6. The date-time version without an offset was local midnight, which is four hours later in UTC. This difference causes the classic "birthday shows a day early" bug for users west of Greenwich. Fixes: parse with an explicit offset, format with an explicit timeZone: "UTC" when the value is a calendar date, or store dates as plain year, month, day numbers and construct them with new Date(Date.UTC(y, m, d)). A calendar date has no time zone, and Temporal's PlainDate models that.

Setters mutate and overflow

A Date is mutable, and every setter changes the object it is called on. Assigning a value out of range rolls into the next unit.

JavaScript
process.env.TZ = "UTC";

const original = new Date(Date.UTC(2026, 0, 31));
const alias = original;

alias.setUTCMonth(1);
console.log(original.toISOString());

const start = new Date(Date.UTC(2026, 0, 31));
const next = new Date(start);
next.setUTCDate(next.getUTCDate() + 1);
console.log(start.toISOString(), next.toISOString());

function addDays(date, days) {
  const copy = new Date(date);
  copy.setUTCDate(copy.getUTCDate() + days);
  return copy;
}

console.log(addDays(start, 30).toISOString());
console.log(start.toISOString());
Text
2026-03-03T00:00:00.000Z
2026-01-31T00:00:00.000Z 2026-02-01T00:00:00.000Z
2026-03-02T00:00:00.000Z
2026-01-31T00:00:00.000Z

Setting the month to February on January 31 gave March 3, since February has no 31st and the extra days rolled forward. And because alias and original are the same object, the change was visible through both names. The safe habit is to copy before changing, as addDays does, and never to pass a date to code that might mutate it. A helper that returns a new date is the substitute for the immutability the type lacks.

Invalid dates fail late

An unparseable string does not throw. It makes a date whose timestamp is NaN, and the failure appears when something uses it.

JavaScript
const bad = new Date("not a date");

console.log(bad.toString());
console.log(bad.getTime(), Number.isNaN(bad.getTime()));
console.log(bad instanceof Date, typeof bad);
console.log(String(new Date(NaN)));
console.log(JSON.stringify({ when: bad }));

try {
  bad.toISOString();
} catch (error) {
  console.log(error.name + ": " + error.message);
}

console.log(new Date("2026-02-30").toString());
console.log(new Date("2026-05-06T25:00:00").toString());
console.log(typeof Date(), typeof new Date());
Text
Invalid Date
NaN true
true object
Invalid Date
{"when":null}
RangeError: Invalid time value
Mon Mar 02 2026 00:00:00 GMT+0000 (Coordinated Universal Time)
Invalid Date
string object

The invalid date is still an object of type Date. It serializes to null in JSON, and toISOString() throws a RangeError. The next two lines show how inconsistent parsing is: V8 accepted February 30 and rolled it to March 2, while an hour of 25 produced Invalid Date, and the specification leaves the handling of such strings to the engine. Check Number.isNaN(date.getTime()) after parsing anything from outside. The last line shows another quirk: calling Date() without new returns a string of the current time and not an object.

Two-digit years and old getters

A year between 0 and 99 in the constructor means 1900 plus that number. The old getYear() returns the year minus 1900.

JavaScript
process.env.TZ = "UTC";

console.log(new Date(99, 0, 1).getFullYear());
console.log(new Date(2099, 0, 1).getFullYear());
console.log(new Date(Date.UTC(99, 0, 1)).getUTCFullYear());

const date = new Date(Date.UTC(2026, 4, 6));
console.log(date.getUTCDay(), date.getUTCDate());
console.log(typeof date.getYear, date.getYear());
Text
1999
2099
1999
3 6
function 126

A year of 99 became 1999 and not 99. getDay() returns the day of the week, from 0 for Sunday, and getDate() returns the day of the month, and mixing them up is a common slip. Use getFullYear() and four-digit years in all new code, and avoid getYear(), which is an obsolete leftover.

Daylight saving and the 24 hour day

A calendar day is not always 24 hours. Adding a day in milliseconds across a daylight saving change moves the wall clock.

JavaScript
process.env.TZ = "America/New_York";

const beforeChange = new Date(2026, 2, 7, 12, 0);
const plus24h = new Date(beforeChange.getTime() + 24 * 60 * 60 * 1000);

const plusOneDay = new Date(beforeChange);
plusOneDay.setDate(plusOneDay.getDate() + 1);

console.log(beforeChange.getHours(), plus24h.getHours(), plusOneDay.getHours());
console.log(plus24h.getDate(), plusOneDay.getDate());
console.log((plusOneDay - beforeChange) / 3600000);

const springForward = new Date(2026, 2, 8, 2, 30);
console.log(springForward.getHours(), springForward.getMinutes());
Text
12 13 12
8 8
23
3 30

Adding 24 hours moved noon to 1 p.m. on March 8, the day the clocks changed, while adding one calendar day with setDate kept noon. The difference between the two results was 23 hours. The last example constructs 2:30 a.m. on the night that time does not exist, and the engine silently moved it to 3:30. A job that must run "every day at 2:30" needs to decide what to do on that day, and Date offers no way to express the decision. The Temporal post shows the explicit rules.

Comparing and copying

Dates compare by value with relational operators and by identity with equality. A date copied by assignment is the same object.

JavaScript
const a = new Date(Date.UTC(2026, 4, 6));
const b = new Date(Date.UTC(2026, 4, 6));

console.log(a === b, a == b);
console.log(a.getTime() === b.getTime(), +a === +b);
console.log(a < b, a <= b, a - b);

const dates = [new Date(Date.UTC(2026, 2, 1)), new Date(Date.UTC(2026, 0, 1))];
console.log(dates.sort((x, y) => x - y).map((d) => d.toISOString().slice(0, 10)));
console.log(Object.is(a, new Date(a)));
Text
false false
true true
false true 0
[ '2026-01-01', '2026-03-01' ]
false

Two equal dates are not ===, because they are different objects, and <= compares timestamps through conversion. Subtraction returns milliseconds, which makes x - y the right sort comparator. Compare with getTime() when you mean equality, and as the post on equality for objects explains, identity is the default for objects.

Formatting

toString(), toLocaleString() and toISOString() give different results, and only the last one is stable across environments.

JavaScript
process.env.TZ = "UTC";

const date = new Date(Date.UTC(2026, 4, 6, 13, 5, 9));

console.log(date.toISOString());
console.log(date.toJSON());
console.log(date.toLocaleDateString("en-US"));
console.log(date.toLocaleDateString("en-GB"));
console.log(date.toLocaleDateString("en-US", { month: "long", day: "numeric", year: "numeric" }));
console.log(date.toLocaleTimeString("en-US", { hour: "2-digit", minute: "2-digit" }));
Text
2026-05-06T13:05:09.000Z
2026-05-06T13:05:09.000Z
5/6/2026
06/05/2026
May 6, 2026
01:05 PM

The ISO form is for machines and storage. The locale forms are for people and follow the viewer's conventions, so 5/6/2026 and 06/05/2026 name the same day, and nothing should parse them back. The Intl post covers formatters in depth.

Habits that avoid the pitfalls

Store timestamps as UTC, as ISO strings with a Z or as epoch milliseconds. Store calendar dates as year, month, day or an ISO date string, and never as a Date at midnight. Parse with explicit offsets and check for NaN afterward. Copy before mutating. Use Date.now() for timestamps and performance.now() for measuring durations, since the system clock can jump. And use calendar methods, setDate or Temporal's add({ days }), to add days, not millisecond arithmetic.

Where Date is still fine

For capturing the current time as a timestamp, Date.now() and new Date() are correct and universal. For formatting a known instant with Intl.DateTimeFormat, a Date is the expected input. And in code that must run where Temporal is not available, a small library of date helpers over Date is the practical choice.

The object is defined in the specification under Date objects, and MDN's Date reference lists every method and the parsing rules.

Share

Keep reading

Get new posts by email

We send one email when a new post is published. No spam.

Unsubscribe in one click. No spam, ever.