How to take system time and add minutes to it in Javascript?

Asked

Viewed 85 times

4

I am making a basic "calculator" for a game, and I need a function that takes the system date and adds 30 minutes when the button is pressed. Follow the script I’m trying to use and it doesn’t work:

function time() {
    var today = new Date();
    h = today.getHours().toString().padStart(2, '0');
    m = today.getMinutes().toString().padStart(2, '0');
    s = today.getSeconds();
    min = m + 30;
    document.getElementById('1').innerHTML = h + ":" + min + ":" + s;
}

When executing it looks like this:

ele apenas concatena

1 answer

5


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>

  • 1

    Buddy, thank you so much, something so simple, and me cracking my head.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.