0

I´m trying to create a code that adds some time (let´s say half an hour) to the current time. I could withdraw current time, but struggle to add the time to it. This is how the code looks so far:

<script>
var dt = new Date();
document.getElementById("datetime").innerHTML = dt.toLocaleTimeString('en', {hour: 'numeric',minute: 'numeric',});

</script>

What could be the possible solution? I am very new to this, so every input is appreciated!

Slaw
  • 37,820
  • 8
  • 53
  • 80
Darina
  • 1
  • Please only use tags relevant to the question (Java != JavaScript). – Slaw Jul 12 '21 at 10:50
  • Possibly related/duplicate: [How to add 30 minutes to a JavaScript Date object?](https://stackoverflow.com/questions/1197928/how-to-add-30-minutes-to-a-javascript-date-object). – Slaw Jul 12 '21 at 10:52
  • 1
    Does this answer your question? [How to add 30 minutes to a JavaScript Date object?](https://stackoverflow.com/questions/1197928/how-to-add-30-minutes-to-a-javascript-date-object) – phuzi Jul 12 '21 at 10:53
  • Does this answer your question? [Adding hours to JavaScript Date object?](https://stackoverflow.com/questions/1050720/adding-hours-to-javascript-date-object) – pratik patel Jul 12 '21 at 10:56

1 Answers1

1

You could add 30 to the minutes part of a Date.

var time = new Date();
time.setMinutes(time.getMinutes() + 30);

This will work correctly in recent versions of NodeJS. Even for adding more minutes than in an hour. e.g. + 120 minutes. However, it is unclear if every implementation of JavaScript will behave the same here. It might be possible for an implementation to just update minutes (and not hours) e.g. 08:48 + 30 might become 08:18 instead of 09:18

janniks
  • 2,942
  • 4
  • 23
  • 36
Luân Bùi
  • 31
  • 1
  • 5
  • "*However, it is unclear if every implementation of JavaScript will behave the same \[when adding more than 60 minutes\]*" actually it's very clear, per [ECMA-262](https://262.ecma-international.org/#sec-date.prototype.setminutes). Any implementation compliant with the standard will allow setting the minutes to any valid number value and will adjust the internal *time value* accordingly. – RobG Jul 13 '21 at 03:33