Function to add more hours or days to a date

Asked

Viewed 39,348 times

18

I don’t know much about function new Date() and wanted a way to add days/hours on a date.

Example:

I have:

var Time = "14/03/2014 23:54";

and I want to add 2 hours to Team, then he adds the 2 hours and adds 1 to the day.

var Time = "15/03/2014 01:54";

If it is in the case of the month it adds 3 and if it comes to the end of the year it already puts as 2015.

I was in need of this urgent code, but I don’t know how to do it (I think it should mess with new Date()). I’m counting on your help!

3 answers

22


Thus:

Hours

var time = new Date('2014-03-14T23:54:00');
var outraData = new Date();
outraData.setHours(time.getHours() + 2); // Adiciona 2 horas

Days

var time = new Date('2014-03-14T23:54:00');
var outraData = new Date();
outraData.setDate(time.getDate() + 3); // Adiciona 3 dias
  • Shouldn’t be var outraData = new Date(time.getTime());?

  • It could be, too. I just wanted to make it clear that it’s a new object.

  • 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?

  • 1

    @Iagobruno I think it’s worth opening a new question to this new doubt.

  • @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 ?

  • @Leonardomacedo I don’t understand your problem.

  • 1

    @I’ve got it all figured out!

  • @Leonardomacedo as resolved?

Show 3 more comments

14

Just to complement: depending on the project, it might be a good idea to use the library Moment js., who takes very good care of this type of situation.

You can do things like this here:

// Criar uma data e adicionar duas horas
var minhaData = moment(
    "14/03/2014 23:54", "D/M/YYYY h:m"
).add(
    'hours', 2
);

// Retornar string "calendário" humanizada
minhaData.calendar(); // "Tomorrow at 1:54 AM" (também dá para fazer em português)

// Retornar objeto Date
minhaData.toDate(); // Sat Mar 15 2014 01:54:00 GMT-0300 (BRT)

10

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.

Browser other questions tagged

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