182

Can anyone give me a simple JavaScript code block that will allow me to display the local time minus 2 hours?

0

2 Answers 2

373

Subtract from another date object

var d = new Date();

d.setHours(d.getHours() - 2);
3
  • 45
    I can confirm (via running in Chrome's Javascript console) that it works with a negative value. That is, d.setHours(d.getHours() - 24) rewinds d to the same time on the previous day. Mar 5, 2015 at 16:44
  • 1
    @InzamamMalik yes it's going to change the date. codepen.io/anon/pen/BxgqzP
    – BrunoLM
    May 25, 2018 at 13:47
  • it may not work for some particular timezones and timestamps (when the clock was moved forward by 2 or more hours)
    – 4esn0k
    Sep 26, 2020 at 20:33
45

According to Javascript Date Documentation, you can easily do this way:

var twoHoursBefore = new Date();
twoHoursBefore.setHours(twoHoursBefore.getHours() - 2);

And don't worry about if hours you set will be out of 0..23 range. Date() object will update the date accordingly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.