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
Parameter | Optional/Required | Description |
---|---|---|
dateString | required | A 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,
- We define a date string
dateString
with the value'January 1, 2021'
. - We use the
Date.parse()
method to convertdateString
to a timestamp. - The timestamp is stored in the variable
timestamp
. - We log
timestamp
to the console usingconsole.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,
- We define a date string
dateString
with the value'2021-01-01T00:00:00Z'
. - We use the
Date.parse()
method to convertdateString
to a timestamp. - The timestamp is stored in the variable
timestamp
. - We log
timestamp
to the console usingconsole.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,
- We define an invalid date string
invalidDateString
with the value'invalid-date'
. - We use the
Date.parse()
method to try to convertinvalidDateString
to a timestamp. - The result is stored in the variable
timestamp
. - We check if
timestamp
isNaN
and log an appropriate message to the console usingconsole.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.