Answering your question itself "Function to add hours or days to a Date":
You want a function to do this for you, well, it’s an easy task, just as you can see in the @Gypsy, may not need a function, but since you whether a function, you can link a Prototype of the object itself Date, which would be to declare the following:
Date.prototype.addHoras = function(horas){
this.setHours(this.getHours() + horas)
};
Date.prototype.addMinutos = function(minutos){
this.setMinutes(this.getMinutes() + minutos)
};
Date.prototype.addSegundos = function(segundos){
this.setSeconds(this.getSeconds() + segundos)
};
Date.prototype.addDias = function(dias){
this.setDate(this.getDate() + dias)
};
Date.prototype.addMeses = function(meses){
this.setMonth(this.getMonth() + meses)
};
Date.prototype.addAnos = function(anos){
this.setYear(this.getFullYear() + anos)
};
Note: In addition to what you requested (hours or days) I also added the functionality for hours, minutes, seconds, days, months and years.
After the declaration of prototype’s you can use them as follows:
//Criando uma data sem parâmetros (tempo atual)
var dt = new Date();
//Exemplo adicionando 1 hora na sua data
dt.addHora(1);
//Exemplo adicionando 30 minutos na sua data
dt.addMinutos(30);
//Exemplo adicionando 15 segundos na sua data
dt.addSegundos(15);
//Exemplo adicionando 10 dias na sua data
dt.addDias(10);
//Exemplo adicionando 2 meses na sua data:
dt.addMeses(2);
//Exemplo adicionando 1 ano na sua data:
dt.addAnos(1);
//Imprimindo ela no console
console.log(dt);
This way you can add hours/minutes/seconds/days/months/years at its date easily.
Shouldn’t be
var outraData = new Date(time.getTime());
?– bfavaretto
It could be, too. I just wanted to make it clear that it’s a new object.
– Leonel Sanches da Silva
Ciganomorrisonmendez, bfavaretto I have a problem, I set a date in the Date function but for some reason comes 3 hours less, ex: "2014-04-25T06:46:00" = "Fri Apr 25 2014 03:46:00 GMT-0300 (Official Time of Brazil)". What causes all this? I tried to use setUTCHours() and put the number 9 (setUTCHours(9)) and came the expected result but it is advisable to use or has another better way?
– Iago Bruno
@Iagobruno I think it’s worth opening a new question to this new doubt.
– Leonel Sanches da Silva
@Ciganomorrisonmendez nesta validação outraData.setDate(time.getDate() + 3); // Adds 3 days I can’t use same month dates, ex: if I put 01/01/2017 I can’t use 20/01/2017, plus I can use 01/02/2017, could help me arumar this ?
– Leonardo Macedo
@Leonardomacedo I don’t understand your problem.
– Leonel Sanches da Silva
@I’ve got it all figured out!
– Leonardo Macedo
@Leonardomacedo as resolved?
– Steve Rogers