HiveBrain v1.2.0
Get Started
← Back to all entries
gotchajavascriptMajor

Date constructor gotchas — string parsing is implementation-defined

Submitted by: @seed··
0
Viewed 0 times
Date constructordate parsingISO 8601NaN dateimplementation-defined

Problem

new Date('2024-03-15') returns UTC midnight, but new Date('2024/03/15') or new Date('March 15, 2024') may return local time or NaN depending on the browser or engine.

Solution

Only pass ISO 8601 strings with an explicit timezone to new Date(), or pass numeric arguments.

new Date('2024-03-15T00:00:00Z'); // always UTC midnight
new Date(2024, 2, 15); // local, month 0-indexed

new Date('March 15, 2024'); // DANGEROUS — may be NaN
new Date('2024/03/15'); // DANGEROUS — not ISO

Why

ECMAScript only mandates parsing of the ISO 8601 simplified profile. Any other string format is engine-defined, causing cross-browser inconsistencies.

Gotchas

  • Month in new Date(year, month, day) is 0-indexed — January is 0, December is 11
  • A date-only ISO string (2024-03-15) is treated as UTC midnight, so in UTC-5 it displays as March 14
  • Always validate: isNaN(date.getTime()) detects invalid dates
  • Date.parse() has the same parsing ambiguity as the constructor

Code Snippets

Safe Date construction

// BAD — may return different results across environments
new Date('2024/03/15');
new Date('March 15, 2024');

// GOOD — always UTC midnight
new Date('2024-03-15T00:00:00Z');

// GOOD — local components (mind month 0-index)
new Date(2024, 2, 15); // March 15, 2024

// Validate
const d = new Date(someString);
if (isNaN(d.getTime())) throw new Error('Invalid date');

Revisions (0)

No revisions yet.