How to convert date to timestamp in JavaScript?

The JavaScript date object is quite rich. We can easily convert the date string to timestamp. We should format the date string properly to get the timestamp.

Instead of converting the date string to something else, it is better to convert it to ISO 8601 format (YYYY-MM-DD). ISO 8601 format is well known by Date() method of JavaScript.

Convert to timestamp examples

Let us consider the following date string:

let dateStr = '2021-03-26 00:00:00';

Approach #1

console.log(new Date(2021,2,26).getTime());
// Month starts from 0 in JS. So, here 2 means March
// Output: 1616695200000

Approach #2

console.log((new Date(dateStr)).getTime());
// Output: 1616695200000

Approach #3

console.log(new Date(2021,2,26).getTime());
// Output: 1616695200000
Share