How to subtract 2 hours from user’s local time with JavaScript?

Sometimes, we want to subtract 2 hours from user’s local time with JavaScript.

In this article, we’ll look at how to subtract 2 hours from user’s local time with JavaScript.

How to subtract 2 hours from user’s local time with JavaScript?

To subtract 2 hours from user’s local time with JavaScript, we can use the setHours method.

For instance, we write

const d = new Date();
d.setHours(d.getHours() - 2);

to create the Date object d which has the user’s current local date time.

Then we call getHours to get the hour of day from date d.

And we subtract that by 2 and use the difference as the argument of setGHours to subtract 2 hours from user’s local time.

Conclusion

To subtract 2 hours from user’s local time with JavaScript, we can use the setHours method.