JavaScript Date.parse() function


The Date.parse() function in JavaScript parses a date string and returns the number of milliseconds since the Unix Epoch (January 1, 1970, 00:00:00 UTC). If the string cannot be parsed, it returns NaN (Not-a-Number).

Syntax:

const milliseconds = Date.parse(string);

Parameters:

  • string: A date string in a format that JavaScript recognizes (usually, ISO 8601 format is recommended).

Returns:

  • The number of milliseconds since January 1, 1970.
  • If the string is invalid or cannot be parsed, it returns NaN.

Example:

1. Valid Date String (ISO Format)

const timestamp = Date.parse("2024-10-22T10:30:00Z"); console.log(timestamp);

Output:

1729593000000

Explanation:

  • The date string "2024-10-22T10:30:00Z" (ISO 8601 format) is parsed to represent October 22, 2024, at 10:30 AM UTC.
  • The function returns 1729593000000, which is the number of milliseconds since the Unix Epoch for that date and time.

2. Non-ISO Format

JavaScript can also parse some other date formats, although support for these formats may vary between browsers.

const timestamp = Date.parse("October 22, 2024 10:30:00"); console.log(timestamp);

Output:

1729593000000

Explanation:

  • The date string "October 22, 2024 10:30:00" is parsed and returns the equivalent milliseconds for the date and time.

3. Invalid Date String

const invalidTimestamp = Date.parse("invalid-date-string"); console.log(invalidTimestamp);

Output:

NaN

Explanation:

  • Since "invalid-date-string" is not a valid date format, Date.parse() returns NaN.

Summary:

  • Date.parse(string) converts a date string into the number of milliseconds since January 1, 1970.
  • It is useful when you want to convert a date string into a timestamp for calculations or comparisons.
  • It is recommended to use ISO 8601 date format (YYYY-MM-DDTHH:mm:ss.sssZ) to ensure compatibility across different environments and browsers.