Why are 2025/05/28 and 2025-05-28 different days in JavaScript?
a year ago
- #JavaScript
- #Time Zones
- #Date Parsing
- JavaScript's Date constructor interprets date strings differently based on their format.
- Dates in the format 'YYYY/MM/DD' are interpreted as local time.
- Dates in the format 'YYYY-MM-DD' (ISO format) are interpreted as UTC, leading to potential day discrepancies when converted to local time.
- The behavior stems from historical inconsistencies in browser implementations and ECMAScript specifications.
- Firefox initially interpreted ISO date-only forms as UTC and date-time forms without offsets as local time.
- Chrome and Safari had their own interpretations, leading to inconsistencies across browsers.
- ECMAScript specifications evolved, but browser implementations remained inconsistent for years.
- Temporal, a new JavaScript API, aims to resolve these issues by introducing plain dates without time zones.
- Temporal requires explicit time zone or offset information when parsing date-time strings, avoiding ambiguity.
- Browser date parsing can be surprisingly lenient, sometimes interpreting invalid strings as valid dates.