JavaScript Date.parse()
Syntax & Examples


Date.parse() static-method

The Date.parse() method parses a string representation of a date and returns the number of milliseconds since January 1, 1970, 00:00:00 UTC. This method is useful for converting date strings into timestamps.


Syntax of Date.parse()

The syntax of Date.parse() static-method is:

Date.parse(dateString)

This parse() static-method of Date parses a string representation of a date and returns the number of milliseconds since 1 January, 1970, 00:00:00 UTC, with leap seconds ignored.

Parameters

ParameterOptional/RequiredDescription
dateStringrequiredA string representing a date. The string should be in a format recognized by the Date.parse() method.

Return Type

Date.parse() returns value of type Number.



✐ Examples

1 Using Date.parse() to convert a date string to a timestamp

In JavaScript, we can use the Date.parse() method to convert a date string to a timestamp in milliseconds.

For example,

  1. We define a date string dateString with the value 'January 1, 2021'.
  2. We use the Date.parse() method to convert dateString to a timestamp.
  3. The timestamp is stored in the variable timestamp.
  4. We log timestamp to the console using console.log() method.

JavaScript Program

const dateString = 'January 1, 2021';
const timestamp = Date.parse(dateString);
console.log(timestamp);

Output

1609459200000

2 Using Date.parse() with a different date format

In JavaScript, we can use the Date.parse() method to parse date strings in various formats. Here, we use the '2021-01-01T00:00:00Z' format.

For example,

  1. We define a date string dateString with the value '2021-01-01T00:00:00Z'.
  2. We use the Date.parse() method to convert dateString to a timestamp.
  3. The timestamp is stored in the variable timestamp.
  4. We log timestamp to the console using console.log() method.

JavaScript Program

const dateString = '2021-01-01T00:00:00Z';
const timestamp = Date.parse(dateString);
console.log(timestamp);

Output

1609459200000

3 Handling invalid date strings with Date.parse()

In JavaScript, if the Date.parse() method is given an invalid date string, it returns NaN.

For example,

  1. We define an invalid date string invalidDateString with the value 'invalid-date'.
  2. We use the Date.parse() method to try to convert invalidDateString to a timestamp.
  3. The result is stored in the variable timestamp.
  4. We check if timestamp is NaN and log an appropriate message to the console using console.log() method.

JavaScript Program

const invalidDateString = 'invalid-date';
const timestamp = Date.parse(invalidDateString);
if (isNaN(timestamp)) {
  console.log('Invalid date string');
} else {
  console.log(timestamp);
}

Output

Invalid date string

Summary

In this JavaScript tutorial, we learned about parse() static-method of Date: the syntax and few working examples with output and detailed explanation for each example.