Can anyone give me a simple JavaScript code block that will allow me to display the local time minus 2 hours?
Asked
Active
Viewed 1.9e+01k times
2 Answers
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
-
44I 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