bluehost-banner

How to Convert a Date String to Unix Timestamp in JavaScript?

In this article, we’ll look at three diffrent ways to convert a date to a UNIX timestamp in JavaScript.

1)Using Date.parse() Method

With using Date.parse() method we can the date string into a timestamp.


Example:

const toTimestamp = (strDate) => {
  const dt = Date.parse(strDate);
  return dt / 1000;
}
console.log(toTimestamp('02/13/2020 23:31:30'));

Here we have created the toTimestamp() method which 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.

2) Using getTime() Method

By usibg the getTime() method of a Date instance to convert the date string into a timestamp.


Example:

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.

After that we divided that by 1000 to get the number of seconds.

3) Using Moment.js’s unix() Method

By using the Moment.js’s unix() method to return a timestamp.


Example:

const toTimestamp = (strDate) => {
  const dt = moment(strDate).unix();
  return dt;
}
console.log(toTimestamp('02/13/2020 23:31:30'));


Here we can use the unix() method which returns the timestamp.

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

Conclusion


As we seen, we can use plain JavaScript or Moment.js to convert a date string into a UNIX timestamp.