Skip to content

Date and Time

JavaScript represents dates and times with the built-in Date object, which internally stores a timestamp (milliseconds since January 1, 1970 UTC β€” the β€œUnix epoch”). Date has a long-standing reputation for an awkward API (zero-indexed months, mutable instances), which is why many projects reach for libraries like date-fns or Temporal (a newer, still-stabilizing standard) for anything non-trivial.

const now = new Date();
const specific = new Date(2026, 5, 15); // June 15, 2026 -- months are 0-indexed!
const fromString = new Date("2026-06-15"); // ISO format, months are 1-indexed here
console.log(now.getFullYear()); // e.g. 2026
console.log(now.getMonth()); // 0-11 (0 = January)
console.log(now.toISOString()); // "2026-06-15T00:00:00.000Z"
const later = new Date(now);
later.setDate(later.getDate() + 7); // add 7 days
const diffMs = later - now; // Date subtraction gives milliseconds
const diffDays = diffMs / (1000 * 60 * 60 * 24);

Confusing the two different month-indexing conventions: new Date(year, month, day) uses 0-indexed months, but new Date("YYYY-MM-DD") string parsing uses 1-indexed months.

const a = new Date(2026, 5, 15); // June 15 -- month 5 means June (0-indexed)
const b = new Date("2026-06-15"); // June 15 -- month 06 means June (1-indexed)
// Both correct, but for DIFFERENT reasons -- easy to mix up and get the wrong month
  1. What does new Date(2026, 0, 1) represent?

    AnswerJanuary 1, 2026 β€” the constructor's month argument is 0-indexed, so 0 means January.
  2. What does subtracting one Date from another give you?

    AnswerThe difference in milliseconds, as a number β€” you need to divide by 1000 * 60 * 60 * 24 etc. to convert to seconds/minutes/days.
  3. Why do many projects avoid the built-in Date object for complex date logic?

    AnswerIts API has well-known rough edges β€” 0-indexed months, mutable instances, awkward timezone handling β€” so libraries like date-fns or the newer Temporal API are often preferred.