How to take the current date and add "n" minutes in this value?

Asked

Viewed 8,101 times

8

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

6 answers

8


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

data.setMinutes(data.getMinutes() + minutos);
  • Are there other methods of this type for other units? Type for seconds or for days.

  • @Miguelangelo You can see the other methods in MDN.

3

Tries:

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

Where diff is the difference in minutes.

3

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

moment.add("minutes", 5);

1

When you have a Date object, calling the method getTime you have the representation of that date in milestones since 01/01/1970. The Date type constructor accepts that you pass a parameter representing milesseconds from that start date to the date you want, if you don’t pass anything it takes the current date.

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

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

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

0

var dtInicio = new Date();
var dtFinal = new Date();
dtFinal.setMinutes(dtInicio.getMinutes()+30);

0

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

Browser other questions tagged

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