Course contentsShow
← JavaScript
Lesson 1635 of 2,72335. Standard Library and Built-insFree lesson

The Date Constructor's Timezone Trap

Learn how `new Date()` interprets strings differently based on format, leading to unexpected timezone shifts.

The Date Constructor's Timezone Trap

You'll learn why new Date(string) can produce wildly different results depending on how you format the string—and how to avoid nasty surprises.

The Hidden Danger

The Date constructor behaves differently based on subtle string format differences. When you pass a date string to new Date(), JavaScript must decide: "Is this a local time or UTC?" The answer depends on the exact format you used.

The trap:

  • ISO 8601 date-only format (like "2024-03-15") is interpreted as UTC midnight
  • Other formats (like "March 15, 2024" or "2024/03/15") are interpreted as local timezone

This means identical calendar dates can produce timestamps that differ by hours:

const isoDate = new Date("2024-03-15");
console.log(isoDate.toISOString());
// "2024-03-15T00:00:00.000Z" (UTC midnight)

const slashDate = new Date("2024/03/15");
console.log(slashDate.toISOString());
// "2024-03-15T05:00:00.000Z" (if you're in EST, 5 hours off!)

Why This Happens

JavaScript follows the ISO 8601 spec: a date-only string without time info is treated as UTC. But non-ISO formats fall back to legacy parsing rules that assume local time. It's like ordering "coffee"—one café gives you black coffee by default, another assumes you want cream and sugar.

The Safe Approach

Always be explicit:

  • Use Date.UTC() when you want UTC
  • Use the year/month/day constructor arguments for local time
  • Never rely on string parsing for production code

Key Takeaway: The same date string with different delimiters (- vs /) triggers different timezone interpretations in new Date(), making string-based date creation dangerously unpredictable.