43

Possible Duplicate:
How to add 30 minutes to a javascript Date object?

I can get the current date object like this:

var currentDate = new Date();

How can I add 20 minutes to it?

var twentyMinutesLater = ?;
Community
  • 1
  • 1
Richard Knop
  • 81,041
  • 149
  • 392
  • 552

6 Answers6

125

Use .getMinutes() to get the current minutes, then add 20 and use .setMinutes() to update the date object.

var twentyMinutesLater = new Date();
twentyMinutesLater.setMinutes(twentyMinutesLater.getMinutes() + 20);
Zsolt Meszaros
  • 21,961
  • 19
  • 54
  • 57
Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
  • 6
    Out of curiosity, does it work in any browser, when minutes is >= 40 ? (IE6 I'm looking at you) – Déjà vu Dec 23 '10 at 10:10
  • 1
    @ring0 - yup, it'll wrap around correctly if adding past the hour, it'll update the hours. – Nick Craver Dec 23 '10 at 10:12
  • 4
    @VGE: *"probably the most efficient way"* Probably not, the raw value method is probably more efficient. But I can't imagine it *remotely matters* in real-world terms, not even in a tight loop, and the code is nice and clear to anyone doing maintenance on it. – T.J. Crowder Dec 23 '10 at 11:00
  • I would not that this will only be right when you are talking about currentDate being "now". If you want to add twenty minutes to any given date, then the declaration should be var twentyMinutesLater = new Date(currentDate); – Jimmy Bosse Jun 16 '13 at 00:17
  • 2
    @JimmyBosse: `new Date(currentDate)` will make a round-trip through a *string* and drop the milliseconds portion of the date. To clone a date accurately (and more efficiently, not that it's likely to matter), you'd want `new Date(+currentDate)`. – T.J. Crowder Feb 23 '16 at 08:21
  • You have to count the minutes in milliseconds. – Vahid Rezazadeh Apr 05 '22 at 08:01
28

Add it in milliseconds:

var currentDate = new Date();
var twentyMinutesLater = new Date(currentDate.getTime() + (20 * 60 * 1000));
T.J. Crowder
  • 1,031,962
  • 187
  • 1,923
  • 1,875
11

Just get the millisecond timestamp and add 20 minutes to it:

twentyMinutesLater = new Date(currentDate.getTime() + (20*60*1000))
Michael Borgwardt
  • 342,105
  • 78
  • 482
  • 720
9

Just add 20 minutes in milliseconds to your date:

  var currentDate = new Date();

  currentDate.setTime(currentDate.getTime() + 20*60*1000);
Déjà vu
  • 28,223
  • 6
  • 72
  • 100
7
var d = new Date();
var v = new Date();
v.setMinutes(d.getMinutes()+20);
Haim Evgi
  • 123,187
  • 45
  • 217
  • 223
pooja
  • 2,334
  • 3
  • 16
  • 16
3

you have a lot of answers in the post

var d1 = new Date (),
d2 = new Date ( d1 );
d2.setMinutes ( d1.getMinutes() + 20 );
alert ( d2 );
Community
  • 1
  • 1
Haim Evgi
  • 123,187
  • 45
  • 217
  • 223