Date.parse for String to Timestamp Conversion
You'll learn how to convert date strings into numeric timestamps using Date.parse(), and why you need to be cautious with non-standard formats.
What is Date.parse()?
Date.parse() takes a date string as input and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC (the Unix epoch). Think of it as a translator that converts human-readable date text into the numeric format JavaScript uses internally.
const timestamp = Date.parse("2024-01-15");
console.log(timestamp); // 1705276800000
// You can use this to create a Date object
const date = new Date(timestamp);
console.log(date); // 2024-01-15T00:00:00.000Z
ISO 8601: The Reliable Format
Date.parse() works most reliably with ISO 8601 formatted strings (YYYY-MM-DD or YYYY-MM-DDTHH:mm:ss.sssZ). This is the international standard format:
Date.parse("2024-03-15T10:30:00.000Z"); // Reliable
Date.parse("2024-03-15"); // Reliable
The Unreliability Problem
Here's the catch: with non-ISO formats, Date.parse() behavior varies across browsers and environments. Different JavaScript engines interpret ambiguous formats differently:
// Risky - different browsers may parse differently
Date.parse("03/15/2024"); // Is this March 15 or day 3, month 15?
Date.parse("15-03-2024"); // Ambiguous format
Date.parse("March 15, 2024"); // Not ISO, less reliable
For non-ISO strings, you might get different timestamps in Chrome vs Firefox vs Node.js. Some may even return NaN (not a number) if parsing fails.
Key Takeaway: Use Date.parse() primarily with ISO 8601 formatted strings for predictable results; avoid relying on it for non-standard date formats, as parsing behavior varies across JavaScript environments.