Categories
JavaScript Answers

How to get the current date minus 20 seconds in JavaScript?

Spread the love

Sometimes, we want to get the current date minus 20 seconds in JavaScript.

In this article, we’ll look at how to get the current date minus 20 seconds in JavaScript.

How to get the current date minus 20 seconds in JavaScript?

To get the current date minus 20 seconds in JavaScript, we can get the timestamp of the date and then we subtract 20000 milliseconds from the timestamp.

For instance, we write:

const d = new Date(2022, 1, 1)
const newD = new Date(d.getTime() - 20000);
console.log(newD)

to create date d.

Then we call d.getTime to return the timestamp of the date in milliseconds.

Next, we subtract 20000 milliseconds from the timestamp to get the timestamp of d minus 20 seconds.

And then we use the returned timestamp to create a new date with the Date constructor.

Therefore, newD is Mon Jan 31 2022 23:59:40 GMT-0800 (Pacific Standard Time) .

Conclusion

To get the current date minus 20 seconds in JavaScript, we can get the timestamp of the date and then we subtract 20000 milliseconds from the timestamp.

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 *