How to subtract 2 hours from user's local time?

JavascriptDate

Javascript Problem Overview


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

Javascript Solutions


Solution 1 - Javascript

Subtract from another date object

var d = new Date();

d.setHours(d.getHours() - 2);

Solution 2 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionEtienneView Question on Stackoverflow
Solution 1 - JavascriptBrunoLMView Answer on Stackoverflow
Solution 2 - JavascriptKostanosView Answer on Stackoverflow