padStart
returns a string, and when you "sum" a string with a number, you’re actually concatenating the number into the string:
let s = '12'; // "s" é uma string
console.log(s + 30); // 1230
So you actually have to add up the 30 minutes before to turn everything into a string:
function time() {
let today = new Date();
today.setMinutes(today.getMinutes() + 30);
let h = today.getHours().toString().padStart(2, '0');
let m = today.getMinutes().toString().padStart(2, '0');
let s = today.getSeconds().toString().padStart(2, '0');
document.getElementById('texto').innerHTML = `${h}:${m}:${s}`;
}
<p id="texto"></p>
<button onclick="time()">vai</button>
Notice also that I have added the 30 minutes using setMinutes
. That’s because if you simply add to the return of getMinutes
can get wrong results. For example, if it is 17:50, getMinutes
will return 50, and you add 30, the result will be 80 and the time would be shown as 17:80 - using the Setter, it already adjusts to the next hour and the result is 18:20).
And another option to format the time is to use toLocaleTimeString
:
function time() {
let today = new Date();
today.setMinutes(today.getMinutes() + 30);
document.getElementById('texto').innerHTML = today.toLocaleTimeString('pt-BR');
}
<p id="texto"></p>
<button onclick="time()">vai</button>
In this case, "pt-BR" corresponds to the Brazilian Portuguese, whose hour format is just what you need (hh:mm:ss).
Another option - if you want to/can use an external lib - is to use Moment js.:
function time() {
document.getElementById('texto').innerHTML = moment().add(30, 'minutes').format('HH:mm:ss');
}
<script src="https://momentjs.com/downloads/moment.min.js"></script>
<p id="texto"></p>
<button onclick="time()">Vai</button>
Buddy, thank you so much, something so simple, and me cracking my head.
– Riberox