Why Does new Date('2021-10-01') Parse as UTC While Other Formats Use Local Time?
This article explains why JavaScript's Date constructor treats ISO‑8601 date‑only strings as UTC but interprets other date formats using the local time zone, detailing V8's parsing logic and showing example outputs in Node.js.
Different ways of writing a date string produce different results in JavaScript.
console.log(new Date('2021-10-01'));
console.log(new Date('2021-10-1'));
console.log(new Date('2021/10/01'));
console.log(new Date('2021/10/1'));
console.log(new Date('2021-10-01 00:00:00'));
console.log(new Date('2021/10/01 00:00:00'));In Node.js the above prints:
2021-10-01T00:00:00.000Z // UTC
2021-09-30T16:00:00.000Z
2021-09-30T16:00:00.000Z
2021-09-30T16:00:00.000Z
2021-09-30T16:00:00.000Z
2021-09-30T16:00:00.000ZThe reason is that strings matching the ISO‑8601 YYYY-MM-DD pattern are interpreted as UTC, while other patterns are treated as local time. V8 follows the ECMA‑262 specification: it first calls ParseES5DateTime for ISO‑8601 strings, which sets the time‑zone offset to zero ( tz->Set(0)).
When the parser finishes, it writes the offset into the result array. If a UTC offset was set, out[DateParser::UTC_OFFSET] receives that value; otherwise it remains NaN. For non‑ISO‑8601 strings without an explicit zone, V8 later replaces NaN with the host’s local offset (e.g., UTC+8), causing the eight‑hour difference.
Thus, new Date('2021-10-01') is parsed as UTC, while formats like 2021/10/01 or those including a time component are parsed using the local time zone, leading to the observed discrepancy.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Node Underground
No language is immortal—Node.js isn’t either—but thoughtful reflection is priceless. This underground community for Node.js enthusiasts was started by Taobao’s Front‑End Team (FED) to share our original insights and viewpoints from working with Node.js. Follow us. BTW, we’re hiring.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
