Categories
Python Answers

How to convert date to timestamp with JavaScript?

Spread the love

Sometimes, we want to convert date to timestamp with JavaScript.

In this article, we’ll look at how to convert date to timestamp with JavaScript.

How to convert date to timestamp with JavaScript?

To convert date to timestamp with JavaScript, we can split the date string with split.

And then we pass the parts into the Date constructor.

For instance, we write

const myDate = "26-02-2022";
const [date, month, year] = myDate.split("-");
const newDate = new Date(year, month - 1, date);
console.log(newDate.getTime());

to call myDate.split with '-' to split the date string by '-'.

Then we create a new Date object with the year, month, and date.

We subtract month by 1 before we pass it into Date since JavaScript date’s months starts ranges from 0 for January and ends with 11 for December.

And then we call getTime to get the timestamp.

Conclusion

To convert date to timestamp with JavaScript, we can split the date string with split.

And then we pass the parts into the Date constructor.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *