How to Fix JavaScript Date Parsing Error
In this tutorial, you'll learn about How to Fix JavaScript Date Parsing Error. We cover key concepts, practical examples, and best practices.
The Problem
new Date() or Date.parse() returns Invalid Date or unexpected dates when parsing non-standard date strings, due to inconsistent cross-browser parsing behavior.
Quick Fix
Step 1: Use ISO 8601 format
The only format guaranteed to parse consistently across browsers:
const date = new Date('2026-06-24T10:30:00Z');
console.log(date.toString());
Wed Jun 24 2026 10:30:00 GMT+0000 (Coordinated Universal Time)
Without timezone, it is treated as UTC in ISO format:
const date = new Date('2026-06-24');
console.log(date.toISOString());
2026-06-24T00:00:00.000Z
Step 2: Use individual arguments
Passing arguments to the Date constructor avoids parsing entirely:
const date = new Date(2026, 5, 24, 10, 30, 0);
console.log(date.toString());
Wed Jun 24 2026 10:30:00 GMT+0000 (Coordinated Universal Time)
Note: months are 0-indexed (5 = June).
Step 3: Parse manually for non-standard formats
For custom date strings like "24/06/2026", parse manually:
function parseDate(str) {
const parts = str.split('/');
if (parts.length !== 3) return new Date(NaN);
const [day, month, year] = parts.map(Number);
return new Date(year, month - 1, day);
}
const date = parseDate('24/06/2026');
console.log(date.toISOString());
2026-06-24T00:00:00.000Z
Step 4: Use a date library
For complex parsing, use date-fns or dayjs:
import { parse, format } from 'date-fns';
const parsed = parse('24.06.2026', 'dd.MM.yyyy', new Date());
console.log(format(parsed, 'yyyy-MM-dd'));
2026-06-24
Prevention
- Always use ISO 8601 format (YYYY-MM-DD) for date strings.
- Prefer the multi-argument constructor over string parsing.
- Validate parsed dates with
!isNaN(date.getTime()). - Use a library like date-fns for complex parsing needs.
- Store dates as UTC timestamps (Unix ms) in databases.
Common Mistakes with date error
- Using
headandtailinstead of pattern matching, causing runtime errors on empty lists - Forgetting that lazy evaluation defers computation until the value is forced, causing space leaks with unevaluated thunks
- Using
returnto exit a function early instead of wrapping a pure value in the monad
These mistakes appear frequently in real-world JS code. DodaTech's contributors have identified these patterns through analysis of open-source projects and production systems.
Practice Exercise
Write a pure function that safely divides two integers using Maybe, then test it with edge cases like division by zero and negative numbers.
This exercise reinforces the concepts covered in this guide. Try implementing it before checking online solutions.
FAQ
Built by the developers of DodaTech
Doda Browser, DodaZIP & Durga Antivirus Pro