Can anyone give me a simple JavaScript code block that will allow me to display the local time minus 2 hours?
2 Answers
Subtract from another date object
var d = new Date();
d.setHours(d.getHours() - 2);
-
45I 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– BrunoLMMay 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)– 4esn0kSep 26, 2020 at 20:33
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.