关于JavaScript中new Date不同日期格式返回日期差一天的技术问询
new Date("yyyy-mm-dd") Gives You a Date One Day Early (And It’s Not a Browser Bug) Great question—this is a super common gotcha with JavaScript date parsing, so let’s break it down clearly.
The Root Cause: ISO 8601 vs. Local Time
Here’s what’s happening: when you pass a date string in yyyy-mm-dd format to new Date(), JavaScript treats this as an ISO 8601 standard date. By spec, ISO dates without a time component are parsed as UTC (Coordinated Universal Time), not your local timezone.
In your example:
new Date("2018-05-13");
This gets interpreted as May 13, 2018 00:00:00 UTC. Since you’re in PDT (GMT-0700), converting UTC to your local time subtracts 7 hours—landing you at May 12, 2018 17:00:00 PDT. That’s why it looks like the date is "one day early."
Why Other Formats Behave Differently
Let’s unpack the other cases you tested:
new Date("05-13-2018"): This is a non-ISO format, so JavaScript falls back to browser-specific parsing rules. Chrome recognizes this as a local date (hence the correct May 13 midnight), but Firefox doesn’t—because there’s no universal standard for non-ISO date strings. Browsers can handle these however they want, which is why you see inconsistencies here.new Date("2018-05-13 00:00:00"): Adding a time component changes the parsing behavior. Without a UTC indicator (likeZat the end), this string is parsed as local time instead of UTC. That’s why you get the expected midnight on May 13.
Is This a Browser Bug?
Nope—this is intentional behavior defined by the ECMAScript specification, not a bug.
Firefox’s behavior might seem different at first, but it’s actually following the same rules. If you were in a timezone ahead of UTC (like UTC+1), new Date("2018-05-13") would show May 13 locally. But in PDT (UTC-7), Firefox should return the same offset as Chrome—maybe your test had a small quirk, but the core spec is consistent across modern browsers.
Fixes for Consistent Date Parsing
If you want reliable, local-time results for yyyy-mm-dd dates, try these approaches:
- Add a local time marker: Append
T00:00:00to the ISO string to force local timezone parsing:new Date("2018-05-13T00:00:00"); // Returns Sun May 13 2018 00:00:00 GMT-0700 (PDT) - Parse the date manually: Split the string and use the
Date(year, monthIndex, day)constructor (remember months are 0-indexed!):const [year, month, day] = "2018-05-13".split("-").map(Number); const date = new Date(year, month - 1, day); // Correct local date - Use a date library: Tools like date-fns or Luxon handle timezone and parsing edge cases out of the box, making date work way less frustrating.
内容的提问来源于stack exchange,提问作者E Net Arch

