Normalize date input
Convert an API date string into an epoch-millisecond value for comparison or storage.
JS Puzzles · Const
Date.parse(str) reads a date from a string and returns its timestamp in milliseconds since 1 January 1970 UTC. Invalid formats produce NaN.
Date.parse(str) interprets a date string and returns the corresponding timestamp: the number of milliseconds since 1 January 1970 in UTC. It accepts the full date-time form or shorter year, year-month, and year-month-day forms; an invalid format produces NaN.
Date.parse(str)| Name | Type | Description |
|---|---|---|
str | string | A date string in the documented date-time format or one of its shorter variants. |
A timestamp: the number of milliseconds from 1 January 1970 UTC+0, or NaN for an invalid format.
const timestamp = Date.parse('2012-01-26T13:51:50.417-07:00');
if (Number.isNaN(timestamp)) {
throw new Error('Invalid date');
}
console.log(timestamp);Parses a date-time string with an explicit offset and prints its millisecond timestamp.
Convert an API date string into an epoch-millisecond value for comparison or storage.
Create a Date instance from a parsed timestamp when date methods are needed.
Validate a date string before accepting it in application input.
Date.parse(str) converts a supported date string into a numeric timestamp measured in milliseconds from 1 January 1970 UTC. It returns NaN when the format is invalid.
Follow-up: How would you safely use the result? Check Number.isNaN(timestamp) before constructing a Date or performing calculations.
The documented full form is YYYY-MM-DDTHH:mm:ss.sssZ. T separates the date and time, the fractional seconds are optional in shorter forms, and Z or a numeric offset supplies time-zone information.
Follow-up: What shorter inputs are supported? YYYY, YYYY-MM, and YYYY-MM-DD are documented shorter variants.
A valid parsed value is a timestamp, meaning milliseconds counted from 1 January 1970 at UTC+0. This numeric result can be passed to the Date constructor to create a Date object.
Follow-up: What should happen for malformed input? Treat NaN as invalid rather than as a usable timestamp.
DateDate constructorDate.parse