2

Could someone help me with this. I need to finish something for a schoolproject which we are displaying tonight and I have to subtract 2 hours from this code. Javascript is totally not my thing.

<a href="urltopage.php"><span id="datetime"></span></a>

<script>
var dt = new Date();
document.getElementById("datetime").innerHTML = dt.toLocaleString();
</script>

I have no idea how to change this. Thanks in advance.

Regards, Justin

Justin Forga
  • 21
  • 1
  • 4
  • 1
    What have you tried? I'm sure there are dozens of question on this site that have example of what you want. First result from a search is: [How do I subtract minutes from a date in javascript?](https://stackoverflow.com/questions/674721/how-do-i-subtract-minutes-from-a-date-in-javascript) Which could be modified to hours. – DBS Aug 21 '20 at 14:34
  • let dt = new Date(Date.now() - 7200); 7200 = 60sec per minute * 60 minutes * 2. – Denis Giffeler Aug 21 '20 at 14:39

2 Answers2

5

Try

var dt = new Date();
dt.setHours(dt.getHours() - 2);
document.getElementById("datetime").innerHTML = dt.toLocaleString();

Have a look here https://codepen.io/vyspiansky/pen/abNBqrx

Ihor Vyspiansky
  • 918
  • 1
  • 6
  • 11
  • you are my HERO! Thank you so much! Just one quick additional question. What if I would want to subtract 2 hours and 7 minutes? – Justin Forga Aug 21 '20 at 14:44
  • I guess, `dt.setMinutes(dt.getMinutes() - 7);` should help to achieve this goal. Demo - https://codepen.io/vyspiansky/pen/KKzNoPR – Ihor Vyspiansky Aug 21 '20 at 14:46
  • I tried that, but guess I had a typo because it didn't work. But now it does, stupid me. You are truly my hero and saved me from a lot of searching. Thanks so much! – Justin Forga Aug 21 '20 at 14:49
-2

You can use moment.js.

moment(dt).subtract(2, 'hours').format();
mkkekkonen
  • 1,704
  • 2
  • 18
  • 35