0 votes

How do I add minutes to an hour I have?

I have a texbox where the current time is shown in 24hrs format, as follows.

 var horaactual= moment(new Date()).format('H:mm'); 
 $('#txthora').val(horaactual);

My objective is to add the current time of the first field with the number of a second field, but I don't know how to indicate that this number interprets them as minutes, since I need it to add them. Example:

txthora: 20:27 - txtnumero: 7. result : 20:34.

I need help to express it in js.

2voto

You can do this with a function that returns the original object and then just format it.

function addMinutes(date, minutes) {
    return new Date(date.getTime() + minutes*60000);
}

var horaactual= new Date(); 
var horamod = moment(addMinutes(horaactual,3)).format("H:mm");

You can find the original code here

2voto

sonEtLumiere Points 136
    var fecha = new Date();
    var hora = fecha.getHours();
    var minutos = fecha.getMinutes();

    if (hora < 10) {hora = "0" + hora};
    if (minutos < 10) {minutos = "0" + minutos};

    var textoHora = `Hora actual: ${hora}:${minutos}`;
    console.log(textoHora);                 

    var numberInput = 15;                   //Acá ingresas el numero que va a sumarse con los minutos
    var newMinutes = minutos + numberInput;

    var counter = 0;    
    for(i = 0; i < newMinutes; i++){  
        counter++;
        if(counter == 60) {
           hora++;
           newMinutes -= 60;
           counter = 0;
        }
    }

    if (hora < 10) {hora = "0" + hora};
    if (newMinutes < 10) {newMinutes = "0" + newMinutes};

    console.log(`Nueva Hora: ${hora}:${newMinutes}`);

HolaDevs.com

HolaDevs is an online community of programmers and software lovers.
You can check other people responses or create a new question if you don't find a solution

Powered by:

X