Darina
Darina

Reputation: 1

JavaScript: Add half an hour to a Locale Time String

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!

Upvotes: 0

Views: 549

Answers (1)

Lu&#226;n B&#249;i
Lu&#226;n B&#249;i

Reputation: 31

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

Upvotes: 1

Related Questions