How do I get the current date and add "n" minutes to this value?

8

I can get the current date simply with new Date() , but how do I add a few minutes to this value? If there is a way to add milliseconds, it can be too.

    
asked by anonymous 29.01.2014 / 17:00

6 answers

8
var data = new Date(),
    minutos = 3;

data.setMinutes(data.getMinutes() + minutos);
    
29.01.2014 / 17:06
3

Try:

var novaData = new Date(velhaData.getTime() + diff*60000);

Where diff is the difference in minutes.

    
29.01.2014 / 17:03
3

It is very difficult to do many things with the object Date . If you'd like more control, consider the moment.js tool. For example, to add 5 minutes:

moment.add("minutes", 5);
    
29.01.2014 / 17:06
1

When you have a Date object, calling the getTime method you have the representation of that date in milliseconds since 01/01/1970. The Date constructor accepts that you pass a parameter representing milliseconds from that initial date to the date you want, if you do not pass anything it picks up the current date.

Then you can create a function that takes its date, the value in minutes, and performs the addition using this idea of the milliseconds in the constructor.

function adicionarMinutos(data, minutos) {
     return new Date(data.getTime() + minutos * 60000);
}

This multiplication by 60000 is to convert minutes to milliseconds. You can do the same type of function to add days, months, seconds, etc., always remembering to convert the desired data to milliseconds.

    
29.01.2014 / 17:06
0
var dtInicio = new Date();
var dtFinal = new Date();
dtFinal.setMinutes(dtInicio.getMinutes()+30);
    
29.01.2014 / 17:13
-1

I indicate the use of the JodaTime API, because it is very worthwhile for simplicity and ease.

    
30.01.2014 / 13:12