Thought leadership from the most innovative tech companies, all in one place.

How to Convert a Date String to Timestamp in JavaScript?

Different ways of converting a date string to a timestamp in JavaScript.

image

Sometimes, we may want to convert a date to a UNIX timestamp in JavaScript.

In this article, we'll look at ways to convert a date to a timestamp in JavaScript.

Use the Date.parse() Method

We can use the Date.parse() method to convert the date string into a timestamp.

For instance, we can write:

const toTimestamp = (strDate) => {
  const dt = Date.parse(strDate);
  return dt / 1000;
};

console.log(toTimestamp("02/13/2020 23:31:30"));

We create the toTimestamp() method that calls the Date.parse() method with a date string to parse it into a timestamp.

The unit is in milliseconds, so we've to divide it by 1000 to convert it to seconds.

Use the getTime() Method

We can use the getTime() method of a Date instance to convert the date string into a timestamp.

To use it, we write:

const toTimestamp = (strDate) => {
  const dt = new Date(strDate).getTime();
  return dt / 1000;
};

console.log(toTimestamp("02/13/2020 23:31:30"));

We create the Date instance with the Date constructor.

Then we call getTime() to return the timestamp in milliseconds.

So we've to divide that by 1000 to get the number of seconds.

Moment.js's unix() Method

We can use the Moment.js's unix() method to return a timestamp.

For instance, we can write:

const toTimestamp = (strDate) => {
  const dt = moment(strDate).unix();
  return dt;
};

console.log(toTimestamp("02/13/2020 23:31:30"));

We pass strDate into the moment() function to return a moment object with the time.

Then we can call the unix() method on that to return the timestamp.

The unix() method returns the timestamp in seconds so we don't have to divide the returned result by 1000.

Conclusion

We can use plain JavaScript or Moment.js to convert a date string into a UNIX timestamp.




Continue Learning