177

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

BrunoLM
  • 97,872
  • 84
  • 296
  • 452
Etienne
  • 7,141
  • 42
  • 108
  • 160

2 Answers2

367

Subtract from another date object

var d = new Date();

d.setHours(d.getHours() - 2);
David Salamon
  • 2,361
  • 25
  • 30
BrunoLM
  • 97,872
  • 84
  • 296
  • 452
  • 44
    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. – Adam Loving Mar 05 '15 at 16:44
  • 1
    @InzamamMalik yes it's going to change the date. https://codepen.io/anon/pen/BxgqzP – BrunoLM May 25 '18 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 '20 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.

Kostanos
  • 9,615
  • 4
  • 51
  • 65