Date and Time
Date and Time
Section titled βDate and TimeβWhat it means
Section titled βWhat it meansβ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.
Examples
Section titled βExamplesβ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. 2026console.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 millisecondsconst diffDays = diffMs / (1000 * 60 * 60 * 24);Common mistake
Section titled βCommon mistakeβ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 monthQuick practice
Section titled βQuick practiceβ-
What does
new Date(2026, 0, 1)represent?Answer
January 1, 2026 β the constructor's month argument is 0-indexed, so0means January. -
What does subtracting one
Datefrom another give you?Answer
The difference in milliseconds, as a number β you need to divide by1000 * 60 * 60 * 24etc. to convert to seconds/minutes/days. -
Why do many projects avoid the built-in
Dateobject for complex date logic?Answer
Its API has well-known rough edges β 0-indexed months, mutable instances, awkward timezone handling β so libraries likedate-fnsor the newerTemporalAPI are often preferred.