Add a few minutes to the one currently obtained

0

Something I must be doing wrong because when I add 5 minutes to the time I just got a result that is not in minutes comes out.

I have the following function in javascript and jquery that I am running with tampermonkey :

// ==UserScript==
// @name        Time Session Intranet
// @namespace   nnn
// @version     1.0
// @description nnn
// @author      nnn
// @match       nnn/*
// @require     https://code.jquery.com/jquery-3.3.1.min.js
// @grant       none
// ==/UserScript==

var $ = window.jQuery;

$(function() {

    $("#usuario").append(contador());

});

function contador() {

    var fecha = new Date();
    var sumarsesion = 5;

    return fecha.getMinutes() + ":" + fecha.setMinutes(fecha.getMinutes() + sumarsesion);

}

And the result I get is the following

  

40: 1533732320697

The first time is well obtained, that is, if we put the page at 14:40, it returns 40 as the first value correctly, but then it would not have to return 45?

What am I doing wrong?

    
asked by David 08.08.2018 в 14:48
source

2 answers

1

just change the counter function by:

function contador() {
    var fecha = new Date();
    var sumarsesion = 5;
    return fecha.getMinutes() + ":" + (fecha.setMinutes(fecha.getMinutes() + sumarsesion) && fecha.getMinutes());
}

or its equivalent

function contador() {
    var fecha = new Date();
    var sumarsesion = 5;
    var minutes = fecha.getMinutes();

    fecha.setMinutes(minutes + sumarsesion);
    return  minutes + ":" + fecha.getMinutes();
}

Your error is that fecha.setMinutes() returns the timestamp of the object fecha , does not return the minutes.

    
answered by 08.08.2018 / 14:57
source
1

What happens is that the setMinutes function returns that value, which is a number representing the milliseconds difference between your Date object and the first of January 1970 . This according to the Documentation

If you do something like:

fecha = new Date();

Then:

fecha.setMinutes(fecha.getMinutes() + 5);

You will have successfully added 5 minutes to your date.

What you should do next, is to show it properly using the necessary methods, if you want to show the minutes, you must use it again:

fecha.getMinutes();

But in your code you tried to concatenate directly the result of setMinutes, which is what I told you above.

    
answered by 08.08.2018 в 14:58