JavaScript Dates: The Traps and How to Avoid Them
The Date object has real pitfalls: timezones, month indexing, and parsing. Learn the traps and the modern alternatives.
By Velloreth
The month trap
Months are zero-indexed.
new Date(2026, 0, 15); // January 15, 2026
new Date(2026, 11, 15); // December 15, 2026
But getDate() for the day of the month is one-indexed.
const d = new Date(2026, 0, 15);
d.getMonth(); // 0 — January
d.getDate(); // 15 — the fifteenth
The inconsistency is a legacy of the original implementation. It is the single most common source of date bugs.
Parsing
The safe way
Use ISO 8601.
new Date('2026-10-26T12:00:00Z'); // UTC
new Date('2026-10-26T12:00:00+05:45'); // with offset
ISO strings with a timezone are parsed consistently across engines.
The unsafe way
new Date('10/26/2026'); // implementation-dependent
new Date('October 26, 2026'); // implementation-dependent
Non-ISO formats are parsed by the engine’s own rules, which differ between browsers and Node versions. A string that parses in Chrome may produce Invalid Date in Safari.
Date-only strings are UTC
new Date('2026-10-26');
A date-only ISO string is parsed as UTC midnight. In a timezone behind UTC, the local representation is the previous day.
// In UTC-5
new Date('2026-10-26').toString();
// 'Sun Oct 25 2026 19:00:00 GMT-0500'
This is a frequent surprise. For a calendar date, use explicit components:
new Date(2026, 9, 26); // local midnight, October 26
Explicit components
new Date(2026, 9, 26, 14, 30, 0, 0);
// year, month (0-indexed), day, hour, minute, second, millisecond
This is unambiguous and always local time.
Instants versus calendar dates
A Date represents an instant in time — a specific moment, measured as milliseconds since the Unix epoch.
A calendar date is different: “October 26” is a date, not an instant. It corresponds to different instants in different timezones.
This distinction is the root of most date confusion. A birthday is a calendar date. A log timestamp is an instant. Using Date for both causes bugs.
// Wrong: a birthday stored as an instant
const birthday = new Date('1990-05-15T00:00:00Z');
// In UTC-5, this displays as May 14
// Right: store the calendar date as a string
const birthday = '1990-05-15';
Timezones
Getting the offset
new Date().getTimezoneOffset(); // minutes behind UTC, e.g. -300 for UTC-5
Note the sign: it is the number of minutes to add to local time to get UTC, so a timezone behind UTC returns a positive number.
UTC methods
d.getUTCHours();
d.getUTCDate();
d.getUTCMonth();
d.toISOString(); // always UTC
Formatting in a timezone
new Intl.DateTimeFormat('en-US', {
timeZone: 'Asia/Kathmandu',
dateStyle: 'full',
timeStyle: 'short',
}).format(new Date());
Intl.DateTimeFormat handles timezones correctly, which the Date getters do not.
Formatting
Intl.DateTimeFormat
The right way for locale-aware output.
const formatter = new Intl.DateTimeFormat('en-GB', {
year: 'numeric',
month: 'long',
day: 'numeric',
});
formatter.format(new Date()); // '26 October 2026'
toLocaleDateString
A shorthand.
new Date().toLocaleDateString('en-GB', {
year: 'numeric',
month: 'short',
day: 'numeric',
});
Relative time
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
rtf.format(-1, 'day'); // 'yesterday'
rtf.format(3, 'hour'); // 'in 3 hours'
A fixed format
For a specific format like YYYY-MM-DD, build it from the getters.
function toISODate(date) {
const y = date.getFullYear();
const m = String(date.getMonth() + 1).padStart(2, '0');
const d = String(date.getDate()).padStart(2, '0');
return `${y}-${m}-${d}`;
}
Note the + 1 for the month.
Arithmetic
Adding days
const tomorrow = new Date(date);
tomorrow.setDate(tomorrow.getDate() + 1);
setDate handles month and year rollover correctly.
Adding months
const nextMonth = new Date(date);
nextMonth.setMonth(nextMonth.getMonth() + 1);
This has a subtle bug: January 31 plus one month gives March 3, because February 31 rolls over. Libraries handle this explicitly.
Differences
const msPerDay = 24 * 60 * 60 * 1000;
const days = Math.round((end - start) / msPerDay);
Subtracting dates gives milliseconds. Note that this counts elapsed time, not calendar days, so a daylight-saving transition makes a “day” 23 or 25 hours.
Comparing
date1 > date2; // works, compares timestamps
date1.getTime() === date2.getTime(); // exact equality
Do not use === on Date objects directly — it compares references.
The library question
For anything beyond simple arithmetic, use a library.
date-fns — functional, tree-shakeable, immutable.
import { addDays, format, differenceInDays } from 'date-fns';
addDays(new Date(), 7);
format(new Date(), 'yyyy-MM-dd');
differenceInDays(end, start);
Day.js — small, Moment-like API.
import dayjs from 'dayjs';
dayjs().add(7, 'day').format('YYYY-MM-DD');
Luxon — from the Moment team, with good timezone support.
import { DateTime } from 'luxon';
DateTime.now().plus({ days: 7 }).toISODate();
DateTime.fromISO('2026-10-26', { zone: 'Asia/Kathmandu' });
Temporal — the future standard, in progress.
Temporal.Now.instant();
Temporal.PlainDate.from('2026-10-26');
Temporal.ZonedDateTime.from('2026-10-26T12:00[Asia/Kathmandu]');
Temporal separates instants, plain dates, plain times, and zoned date-times, which fixes the conceptual confusion in Date. It is available behind a polyfill and is being implemented in engines.
Storing and transmitting dates
The convention that avoids most problems: store and transmit instants as ISO 8601 strings in UTC, and convert to local time only for display.
// Store
const createdAt = new Date().toISOString(); // '2026-10-26T10:15:00.000Z'
// Transmit
fetch('/api/events', {
method: 'POST',
body: JSON.stringify({ createdAt }),
});
// Display
new Intl.DateTimeFormat('en-GB', {
dateStyle: 'medium',
timeStyle: 'short',
}).format(new Date(createdAt));
The benefits:
- Unambiguous. An ISO string with a
Zsuffix is a specific instant. - Sortable. ISO strings sort lexicographically in the same order as chronologically.
- Portable. Every language and database parses ISO 8601.
- Comparable. String comparison works for ordering.
For calendar dates — birthdays, holidays, deadlines — store the date as a plain YYYY-MM-DD string, not as an instant. A birthday is not a moment in time, and storing it as one introduces timezone bugs.
// Wrong: a birthday as an instant
const birthday = new Date('1990-05-15T00:00:00Z');
// Right: a calendar date as a string
const birthday = '1990-05-15';
Validating dates
new Date('invalid') produces an Invalid Date, which is a Date object whose time value is NaN.
const d = new Date('not a date');
isNaN(d.getTime()); // true
The check is isNaN(date.getTime()), because isNaN(date) coerces the object to a number, which happens to work but is less explicit.
function isValidDate(d) {
return d instanceof Date && !isNaN(d.getTime());
}
Note that Invalid Date is still an instance of Date, so the instanceof check alone is not enough.
Common tasks
A few date operations come up constantly, and each has a correct form.
Start of day. Set the time components to zero.
const start = new Date(date);
start.setHours(0, 0, 0, 0);
End of day. Set to the last millisecond.
const end = new Date(date);
end.setHours(23, 59, 59, 999);
Days between two dates. Divide the millisecond difference.
const days = Math.round((end - start) / 86400000);
Check if a date is today. Compare the date components, not the timestamps.
function isToday(date) {
const now = new Date();
return date.toDateString() === now.toDateString();
}
Format for an input field. The datetime-local input expects a specific format.
function toInputValue(date) {
const pad = (n) => String(n).padStart(2, '0');
return `${date.getFullYear()}-${pad(date.getMonth() + 1)}-${pad(date.getDate())}T${pad(date.getHours())}:${pad(date.getMinutes())}`;
}
A note on testing
Dates are hard to test because they depend on the current time. A test that calls new Date() produces a different result every run, which makes it flaky. The fix is to inject the clock rather than reading it directly. A function that takes a now parameter is testable; one that calls Date.now() internally is not. The same applies to timezones: a test that assumes the machine’s timezone will fail on a CI runner configured differently. Set the timezone explicitly in the test environment, or use UTC throughout and convert only at the edges.
Practical guidance
- Remember months are zero-indexed and days are not.
- Use ISO 8601 for parsing and storage.
- Use explicit components for calendar dates.
- Store instants as UTC ISO strings and convert for display.
- Use
Intl.DateTimeFormatfor locale-aware output. - Use a library for arithmetic and timezone work.
- Distinguish instants from calendar dates in your data model.
- Watch the date-only UTC parsing trap.
For the related guides, see javascript-modules-guide and javascript-optional-chaining. For the broader context, json-vs-yaml-vs-toml and cron-expressions-explained.
Quotable summary
Months are zero-indexed in the Date constructor, so January is 0, while getDate() for the day of the month is one-indexed, which is a constant source of off-by-one bugs. Date parsing of non-ISO strings is implementation-dependent, so always use ISO 8601 or explicit component arguments, and note that a date-only ISO string is parsed as UTC midnight, which can display as the previous day in timezones behind UTC. A Date represents an instant in time, not a calendar date, and confusing the two is the root of most date bugs. Store and transmit dates as ISO 8601 strings in UTC and convert to local time only for display, using Intl.DateTimeFormat for locale-aware output. For anything beyond simple arithmetic, use date-fns, Day.js, Luxon, or Temporal.