1

I would like to add 20 minutes to the current date. While browsing the messages already posted on this subject, I recovered a piece of code but I can not adapt it. Can you help me ?

// get the current date & time
var dateObj = Date.now();

// I do not understand what these values ​​are
dateObj += 1000 * 60 * 60 * 24 * 3;

// create a new Date object, using the adjusted time
dateObj = new Date(dateObj);
5
  • 4
    date.setMinutes()? Commented Aug 14, 2019 at 10:04
  • 1
    1000 * 60 * 60 * 24 * 3 is three days in milliseconds.
    – Teemu
    Commented Aug 14, 2019 at 10:06
  • 3
    "I do not understand what these values ​​are" 1000 (milliseconds in a second), 60 (seconds in a minute), 60 (minutes in an hour), 24 (hours in a day), 3 (days).
    – phuzi
    Commented Aug 14, 2019 at 10:06
  • new Date(Date.now()+20*60*1000); Commented Aug 14, 2019 at 10:07
  • date.setMinutes(date.getMinutes() + 20)
    – phuzi
    Commented Aug 14, 2019 at 10:08

6 Answers 6

4

Create a prototype function on Date Object if you want to use it in various places as it will reduce redundancy of code.

Date.prototype.add20minutes = function(){
 return this.setMinutes(this.getMinutes() + 20);
}

Now, you can simply call

var d = new Date();
d.add20minutes(); 
1
  • Be advised that in my testing, the foregoing returned a 32-bit integer that needed to be cast to a new Date object. Commented Apr 16, 2023 at 6:32
2

Use this piece of code

var date = new Date();
date.setMinutes(date.getMinutes()+20);
2

Don't know if setMinutes with values > 60 is defined or it works by accident. You can do it this way:

var current_ms = new Date().getTime();
var in20min = new Date(current_ms + (1000*60*20))
1

JavaScript Date object has a method called setMinutes

let d = new Date()

d.setMinutes(d.getMinutes() + 20)

1

In javascript when working with dates I like to use moment:

https://momentjs.com/

So you can do this:

moment().add(20, 'minutes');

1

Use this code:

var date = new Date();
var min = parseInt(date.getMinutes()+20);
date.setMinutes(min);

Not the answer you're looking for? Browse other questions tagged or ask your own question.